0

I have been trying to use the Facebook login API in AngularJS. But I am not able to update a variable.

$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
}

The first console.log() shows the correct data in $scope.name, i.e. only in FB.api. But the others do not show the updated value.

michal.jakubeczy
  • 8,221
  • 1
  • 59
  • 63
MOHIT
  • 1
  • First, is there a reason for not having a semicolon at the end of line 3? Second, at the risk of verifying the obvious... are you checking in the console to ensure invocation of FB.api isn't resulting in an error? – dat Aug 20 '16 at 22:23
  • Possible duplicate of [How do I return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – JLRishe Aug 22 '16 at 05:58

1 Answers1

2

That's because your code is asyncronous in the fb.api call, and your $scope.name is not yet assigned.

In your code:

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 may need 1, 100 or xxxms of delay to perform (and execute the inner function). Your console log below it, however ( //2) it's called immediately after the execution of fb.api function (and not his resolve) so your $scope.name it's not assigned already.

For more info, read some tutorial on async callback and promises on javascript.

illeb
  • 2,942
  • 1
  • 21
  • 35