[英]Angular JS promises, JSON data and funny timings
I'm really struggling with the promises here. 我真的在兑现诺言。
It's more than a day now, and I still can't figure it out. 现在已经超过一天了,我仍然无法解决。
I'm new to Angular and, more in general, to the promises "concept", so I'm sure there is something I'm missing, but I can't figure it out. 我是Angular的新手,更笼统地说,是诺言“概念”的新手,所以我确定我缺少一些东西,但我无法弄清楚。
Basically, I'm calling a remote web service using a $post
request, and in the success
method I update some data on $rootScope
基本上,我使用
$post
请求调用远程Web服务,并以success
方法更新$rootScope
上的一些数据。
LoginService LoginService
this.login = function(url, request) {
return $http.post( url, request ).
success(function(data) {
if (data.return_code === 0) {
userData = {
name: data.name,
role: data.role
}
/*
* Inside this function, $rootScope gets
* updated with userData
*/
storage.update('user_details', userData)
}
else {
// non authorized user
}
return userData
}).
error(function(data, status) {
throw new Error()
})
}
Then, in the controller, I do something like 然后,在控制器中,我执行类似
$scope.login = function(url, request) {
loginService.login(url, request).then(function(response) {
/* this is a ui.router redirection to the state 'home' */
$state.go('home')
})
}
The problem is that in the new page (the home
state), $rootScope is not updated, unless I do a page reload, which "solves" the issue. 问题是在新页面(
home
状态)中,$ rootScope不会更新,除非我重新加载页面才能“解决”该问题。
It seems to me that the call of the promise does not wait for it's completion for the page redirect, but even wrapping $state.go in a $timeout doesn't solve the issue... 在我看来,promise的调用不会等待页面重定向完成,但是即使将$ state.go封装在$ timeout中也无法解决问题...
I'm really lost, any help would be appreciated 我真的迷路了,不胜感激
If storage update is some async action you want to wait for until it is complete and it returns a promise then you can simply chain it: 如果存储更新是异步操作,您要等到更新完成并返回promise,然后您可以简单地将其链接:
this.login = function(url, request) {
return $http.post(url, request).then(function(data){
if (data.return_code === 0) {
var userData = {
name: data.name,
role: data.role
};
return storage.update('user_details', userData).then(function(){
return userData;
});
}
else {
}
})
};
In usage: 使用中:
loginService.login(...).then(function(userData){
//You reach here only after storage.update was completed
$state.go('home')
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.