2016-01-06 61 views
0

我需要多個區域的用戶詳細信息。我試圖用通用函數返回細節。但我得到的結果爲undefined。我明白,我需要使用$differed才能獲得重新使用。但我對目前的情況並不瞭解。

有人幫我在這裏嗎?

這裏是我的功能:

$scope.currentUserInfo = function() { 

     var userDetails; 

     server.getProfile.get().$promise.then(function (response) { 

      if(response.Message.toUpperCase().indexOf('SUCCESS') != -1) { 

       return userDetails = response; 

      } 

      return "Not able to get the user details this time" 

     }) 

     return userDetails; 

    } 

$scope.currentUser = $scope.currentUserInfo(); 
console.log($scope.currentUser) //undefined. 



var function1 = function() { 

    $scope.currentUserInfo(); //once user details available do further 

    $scope.age = $scope.currentUser.age; 

} 

var function2 = function() { 

    $scope.currentUserInfo(); //once user details available do further 

    $scope.name = $scope.currentUser.name; 

} 
+0

可能的重複[如何從異步調用返回響應?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-an-asynchronous-call) – Grundy

回答

1

server.getProfile.get()是一個異步調用。 即使server.getProfile.get()調用還沒有完成,也會執行函數$scope.currentUserInfo函數。 試試這個:

$scope.currentUserInfo = function() { 

    server.getProfile.get().$promise.then(function (response) { 

     if(response.Message.toUpperCase().indexOf('SUCCESS') != -1) { 

      $scope.currentUser = response; 

     } 

     $scope.message = "Not able to get the user details this time"; 


    }) 

} 

$scope.currentUser將填充後的Ajax調用完成。我假設你在你的HTML綁定中使用$scope.currentUser,所以當值改變時它會自動反映在你的視圖中

+0

我同意。但是,直到我從'$ scope.currentUser'接收到值,我想'暫停'其他函數 - 怎麼辦? – 3gwebtrain

+0

暫停其他功能是什麼意思? – PrinceG

+0

讓我更新代碼 – 3gwebtrain