2016-08-20 106 views
0

我一直在嘗試在AngularJS中使用Facebook登錄API。但我無法更新變量。AngularJS中的全局變量未更新

$scope.init = function() { 
    $scope.name = "" 
    window.fbAsyncInit = function (response) { 
     FB.init({ 
      appId: 'xxxxxxxxxxxxxxxxxxx', 
      xfbml: true, 
      version: 'v2.7' 
     }); 
     FB.getLoginStatus(function (response) { 
      if (response.authResponse) { 
       //Calling Fb graph api if user is log in and fetching name of user 

       FB.api('/me', { 
        fields: 'name' 
       }, function (response) { 
        $scope.name = response.name; 
        console.log($scope.name); // 1 
       }); 
       console.log($scope.name); // 2 

      } 
     }); 
    }; 
    console.log($scope.name); // 3 
} 

第一console.log()表示$scope.name正確的數據,即,僅在FB.api。但其他人不顯示更新的價值。

+0

首先,是否有理由在第3行末尾沒有分號?其次,冒着驗證顯而易見的風險...你是否檢查控制檯以確保調用FB.api不會導致錯誤? – dat

+0

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

回答

2

這是因爲您的代碼在fb.api調用中是異步的,並且您的$ scope.name尚未分配。

在您的代碼:

FB.api('/me',{fields: 'name'}.function(response) 
{ 
    $scope.name=response.name; //$scope.name is assigned 
    //1 
    console.log($scope.name); 
}); 

// 2 
console.log($scope.name); //$scope.name is not YET assigned, because i'm called first! 

Fb.api可能需要延遲的1,100個或xxxms執行(並執行內部功能)。你的控制檯記錄在它下面,但是(// 2)在執行fb.api函數(而不是他的解析)之後立即調用它,所以你的$ scope.name它不會被分配。

欲瞭解更多信息,閱讀一些關於異步回調的教程,並在JavaScript上承諾。