我有一个简单的问题,我似乎无法破解。
在我调用下一个函数时,似乎没有分配$ rootScope中的变量,但这不是Promise(.then)的意义吗?
我的堆栈是AngularJS v1.6.4和NodeJS,但这是一个纯粹的Angular问题
我的代码段在下面放置console.log及其响应的位置。
mainApp.controller('navBarController', ['$scope', '$rootScope', '$http', function($scope, $rootScope, $http){
var checkIfAuthenticated = function(){
return $http.get('/api/isAuthenticated');
};
var getProfileID = function(){
return $http.get('/session');
};
var getUser = function(profileID){
console.log('This is the profileID when passed into getUser: ' + profileID); //this shows undefined
return $http.get('/api/user', {params: {_id: profileID}})
};
checkIfAuthenticated()
.then(function(res) {
if(res.status==200){
$rootScope.userLoggedIn = true;
};
})
getProfileID()
.then(function(res) {
if($rootScope.userLoggedIn === true){
$rootScope.profileID = res.data._id;
console.log('This is the profileID when getProfileID is called: ' + $rootScope.profileID); //this shows the correct ID
};
})
getUser($rootScope.profileID)
.then(function(res) {
if($rootScope.userLoggedIn === true){
$rootScope.profilePic = res.data.user.profilePic;
};
});
}]);
如果有人可以解释发生了什么,将不胜感激。
谢谢
要将数据从一个承诺传递到另一个承诺,请将它们链接起来:
checkIfAuthenticated()
.then(function(res) {
if(res.status==200){
$rootScope.userLoggedIn = true;
return getProfileID();
} else {
throw "Not Logged In";
}
}).then(function(res) {
$rootScope.profileID = res.data._id;
console.log('This is the profileID when getProfileID is called: '
+ $rootScope.profileID); //this shows the correct ID
return getUser($rootScope.profileID);
}).then(function(res) {
if($rootScope.userLoggedIn === true){
$rootScope.profilePic = res.data.user.profilePic;
};
});
由于调用.then
promise方法将返回新的派生promise,因此很容易创建promise的链。可以创建任意长度的链,并且由于一个承诺可以用另一个承诺来解决(这将进一步推迟其解决方案),因此可以在链中的任何点暂停/推迟对承诺的解决。
有关更多信息,请参见
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句