0
我想在特定的函數調用結束後爲$ scope變量賦值。但是由於JS引擎異步處理請求,它在函數調用結束之前分配變量。我該如何解決這個問題。下面是我試圖在fblogin函數調用後分配$ scope變量isAuth,msg,profpic等的代碼片段。
//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
}]);