之前我使用AngularJS,UI路由器和$资源REST风格的Web服务。
在HTML视图的按钮被点击调用下面函数即$ scope.login()。因此REST服务(通过$资源)被调用,并在情况下,用户会返回一个用户名/密码是正确的,
$scope.login = function() {
myfactory.get({
email: $scope.user.email,
password: $scope.user.password
},function(user) {
accessmgr.grantAccess(user); //Line of interest - loi1
$state.go('app.dashboard-v1'); //Line of interest2 - loi2
}, function(x) {
if (x.status == 401)
$scope.authError = 'Email or Password not right';
else
$scope.authError = 'Server Error! Are you connected to internet?';
});
}
万一
以上的成功执行,另一家工厂的功能(loi1以上)被调用,以存储用户的实例中$ localStorage如下;
myapp.factory('accessmgr', function($localStorage) {
//var User = {};
return {grantAccess: function(usr) {
$localStorage.user = usr;
}
}});
和ui-router $ scope.go(...)将用户带到仪表板。
问题: 有时 $ state.go(...)accessmgr.grantAccess之前执行(...)导致异常作为新的国家从还没写$的localStorage读取用户。手动重新加载页面可以解决问题。
任何帮助将非常感激。
等待承诺从''grantAccess''然后执行$ state.go像返回''accessmgr.grantAccess(用户)。然后(功能(响应){$ state.go( 'app.dashboard-V1'); })'' –
我认为promise/then仅适用于$ http或$ resource之类的回调?在我的情况下,它只是另一个功能将用户保存到$ localStorage。无论如何,我尝试过,但报道对铬'类型错误的控制台错误:无法为$ promise.then'读undefined'的属性“然后”与同类型错误:无法读取性能undefined' – hammad
承诺的“$承诺”可以用来与任何异步服务,只要服务是基于承诺(和$ localStorage不是)。 – estus