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.

2
  • 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? Commented Aug 20, 2016 at 22:23
  • Possible duplicate of How do I return the response from an asynchronous call? Commented Aug 22, 2016 at 5:58

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.