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

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

问题描述

我将 AngularJS、ui-router 和 $resource 用于 RESTful 网络服务.

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

点击 html 视图中的一个按钮,调用下面的函数,即 $scope.login().因此,调用 REST 服务(通过 $resource)并在 user/pass 正确的情况下返回用户,

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-router $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.

任何帮助将不胜感激.

推荐答案

ngStorage 的 $localStorage 不能在不使用 watchers 的情况下直接引用(不推荐根据 此处,或者可以将其作为引用传递给 $scope 挂钩,如推荐方法 此处.

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 在前一条语句执行完成之前执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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