initUserProfile: function() {
return $http.get('myapi/user/profil').
then(function(response) {
current_user = response.data;
if (current_user.profilpicture) {
current_user.profilpicture = $rootScope.baseURL + "/images/users/" + current_user.username + "/" + current_user.profilpicture;
}
}, function(err) {
// log error
});
};
我希望它返回一个 promise ,这里就是这种情况,但它是 $http 成功 promise 。 当 then() 内的更改完成时,我该如何返回 promise ?
最佳答案
只需在 then()
中返回 current_user
,它将可作为链中下一个 then()
的参数
initUserProfile: function() {
return $http.get('myapi/user/profil').
then(function(response) {
current_user = response.data;
if (current_user.profilpicture) {
current_user.profilpicture = $rootScope.baseURL + "/images/users/" + current_user.username + "/" + current_user.profilpicture;
}
return current_user;
}).catch(function(err) {
// log error
});
};
在 Controller 中:
myService.initUserProfile().then(function(current_user){
$scope.user = current_user;
})
关于javascript - 在$http.then()中做事,然后返回promise,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38510378/