2016-08-20 110 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上承诺。