AngularJS $ state.go执行previous语句执行完毕之前 [英] AngularJS $state.go executes before previous statement execution completes

查看:401
本文介绍了AngularJS $ state.go执行previous语句执行完毕之前的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用AngularJS,UI的路由器和$资源REST风格的web服务。

I am using AngularJS, ui-router and $resource for RESTful webservices.

在HTML视图中的按钮被点击调用下面函数即$ scope.login()。因此REST服务(通过$资源)被调用,并在情况下,用户会返回一个用户名/密码是正确的,

A button in html view is clicked that calls below function i.e. $scope.login(). Consequently a REST service (through $resource) is called and returns a user in case user/pass are correct,

$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存储用户实例;

in case above successfully executes, another factory function (loi1 above) is called to store user instance in $localStorage as below;

myapp.factory('accessmgr', function($localStorage) {
    //var User = {};
    return {grantAccess: function(usr) {
            $localStorage.user = usr;
        }
    }});

和UI路由器$ scope.go(...)把用户带到仪表板。

and ui-router $scope.go(...) takes the user to dashboard.

问题:
有时的$ state.go(...)之前accessmgr.grantAccess(...)造成的异常作为新的国家从还没写$的localStorage读取用户执行。重新加载页面手动解决问题。

Problem: Sometimes $state.go(...) executes before accessmgr.grantAccess(...) causing exceptions as the new state reads user from $localStorage that is not yet written. Reload the page manually solves the problem.

任何帮助将是非常美联社preciated。

Any help would be really appreciated.

推荐答案

ngStorage的$ localStorage的,不能直接使用,而不提及观察家(不推荐按的这里,或者也可以一样推荐的方法的这里

ngStorage's $localStorage cannot be referred directly without using watchers (not recommended as per here, alternatively it can to be passed as a reference to hook to $scope as mentioned as recommended approach here.

对于我来说,我是用$ localStorage的通过工厂和我绑它下面rootScope;

For me, I was using $localStorage through a factory and I tied it to rootScope as below;

$rootScope.$storage = $localStorage;

,因此

myapp.factory('accessmgr', function($localStorage) {
  $rootScope.$storage = $localStorage;
  return {
    grantAccess: function(usr) {
        $rootScope.$storage.user = usr;
      },
    getUser: function() {
        return $rootScope.$storage.user;
      }
  }});

这篇关于AngularJS $ state.go执行previous语句执行完毕之前的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆