I’m trying to assign values to $scope variables after a particular function call is over. But since JS engine processes requests asynchronously it assigns the variables before the function call is over. How do I resolve this. Below is the code snippet where I’m trying to assign $scope variables isAuth,msg,profpic etc after the fblogin function call.
//controller
ub.controller('mainController',['$scope','$log','$http','fbauthFact','$location','$anchorScroll','$routeParams',function($scope,$log,$http,fbauthFact,$location,$anchorScroll,$routeParams){
$scope.profpic="";
$scope.msg={};
$scope.fblogin= function(){
$scope.fblogincb(function callback(){
$scope.isAuth = fbauthFact.isAuth;
$scope.msg= fbauthFact.msg;
$scope.profpic=fbauthFact.profpic;
$scope.accesstoken=fbauthFact.accesstoken;
$log.log("$scope.msg: "+$scope.msg);
$log.log("$scope.isAuth:"+$scope.isAuth);
});
};
$scope.fblogincb=function(callback){
fbauthFact.fblogin();
callback();
};
}]);
//service
ub.service('fbauthFact',["$http","$log","$rootScope",function($http,$log,$rootScope){
this.isAuth=false;
this.profpic=""
this.fbresponse={};
this.msg="";
var self=this;
self.testAPI =function() {
FB.api('/me',{fields: 'first_name,last_name,gender,email,picture'}, function(response) {
this.fbresponse = response;
this.profpic = response.picture.data.url;
this.isAuth=true;
this.accesstoken = FB.getAuthResponse().accessToken;
document.getElementById('status').innerHTML =
'Thanks for logging in, ' + response.first_name + '!';
document.getElementById('profpic').innerHTML =
"<img src='" + response.picture.data.url + "'>";
$http({
method:"GET",
url: "http://localhost:3000/api/creaprof",
params: response
}).then(function successCallback(srresponse){
this.msg=srresponse.data;
$log.log("http get request success: "+this.msg);
},
function errorCallback(srresponse){
$log.log("http get request failure"+srresponse.data);
});
$rootScope.$apply();
});//FB.api call back function
};//testAPI
this.fblogin =function(){
FB.login(function(response){
if (response.status === 'connected') {
// Logged into your app and Facebook.
self.testAPI();
} else if (response.status === 'not_authorized') {
// The person is logged into Facebook, but not your app.
document.getElementById('status').innerHTML = 'Please log ' +
'into this app.';
} else {
// The person is not logged into Facebook, so we're not sure if
// they are logged into this app or not.
document.getElementById('status').innerHTML = 'Please log ' +
'into Facebook.';
}
});
};//fblogin
}]);
2
Answers
thanks @Salih. your answer helped me to use $q service with promise to resolve my issue. But I had to use it in a different places. Here's my working code.
In your Service, change fblogin method like below so that it returns a promise.
Then in your controller call it like