API获取数据之前运行

API获取数据之前运行

本文介绍了$ stateChangeStart从REST API获取数据之前运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试着做用户登录验证,我做了一个名为服务 AuthService 用的方法 isAuthenticated 中,我打个电话给API来交叉检查用户登录或没有(另外我会在用户在以后的用户角色),然后我称之为 $ rootScope此服务。$在,但它不是等到我的服务获得API的数据,这是我的app.js

  VAR应用= angular.module('对myApp',['ngRoute','ui.router','ngAnimate,烤面包机,ui.bootstrap']);的app.config(['$ routeProvider','$ locationProvider','$ stateProvider','$ urlRouterProvider',
  功能($ routeProvider,$ locationProvider,$ stateProvider,$ urlRouterProvider){
        $ stateProvider。
        状态('/',{
            网址:/,
            观点:{
                标题:{
                    templateUrl:'谐音/普通/ header.html中',
                    控制器:'authCtrl',
                },
                内容:{
                    templateUrl:'谐音/ dashboard.html',
                    控制器:'authCtrl',
                }
            },
            标题:仪表板,
            验证:真
        })        .STATE('登陆',{
            网址:/登录
            观点:{
                内容:{
                    templateUrl:'谐音/ login.html的,
                    控制器:'authCtrl',
                }
            },
            标题:登录,
            验证:假的
        })        .STATE(仪表盘,{
            标题:仪表板,
            网址:/仪表板,
            观点:{
                标题:{
                    templateUrl:'谐音/普通/ header.html中',
                    控制器:'authCtrl',
                },
                内容:{
                    templateUrl:'谐音/ dashboard.html',
                    控制器:'authCtrl',
                }
            },
            验证:真
        });
        $ urlRouterProvider.otherwise(/);        //检查浏览器支持
        如果(的window.history&安培;&安培; window.history.pushState){
            $ locationProvider.html5Mode({
                 启用:真实,
                 requireBase:假的
            });
        }
  }])
 .RUN(函数($ rootScope,$位置$状态数据,AuthService){
        $ rootScope。在$($ stateChangeStart功能(事件,toState,toParams,fromState,fromParams){
            $ rootScope.title = toState.title;
            $ rootScope.authenticated = FALSE;
            VAR USERINFO = AuthService.isAuthenticated();
            如果(toState.authenticate&放大器;&放大器;!AuthService.isAuthenticated()){
                  //用户没有通过验证
                  $ state.transitionTo(登录);
                  。事件preventDefault();
            }其他{
               警报('我在这里='+ $ rootScope.authenticated);
            }
        });
    });

下面是我的服务

  app.factory('AuthService',函数($ HTTP,数据,$ rootScope){
  变种authService = {};  authService.isAuthenticated =功能(){
    Data.get('的index.php / API /认证/ is_login'),然后(功能(结果){
        如果(results.uid){
            $ rootScope.authenticated =真;
            $ rootScope.uid = results.uid;
            $ rootScope.name = results.name;
            $ rootScope.email = results.email;
            返回results.uid;
        }其他{
            返回false;
        }
    });
  }
  返回authService;
});

试过很多东西,但至今没有运气,请建议做一个最好的方法,我试过在UI的路线的决心方法,但没有奏效。

先谢谢了。


解决方案

这是您目前将无法工作,因为 Data.get()函数返回的实施无极,并且是异步的。正因为如此,该航线变化将继续,而不必等待,直到你的身份验证服务返回的任何值。

要解决您的问题,您应该以特定方式处理这种异步逻辑:

  app.run(函数($ rootScope,$位置$状态数据,AuthService){
  $ rootScope。在$('$ stateChangeStart',函数(事件,toState,toParams,fromState,fromParams){
    / **
     *如果用户正在走向一个需要国家标题
     *认证,假设他们没有通过身份验证,
     *阻止他们!否则,让他们通过...
     * /
    如果(toState.authenticate){
      。事件preventDefault();      如果(toState.name!== fromState.name){
        //现在检查它们是否被验证
        AuthService.isAuthenticated()。然后(函数(){
          //没错!他们验证,继续
          $ state.go(toState.name,toParams);
        },函数(){
          //不,该用户不能查看此页
          警报('你不能查看此页!');
        });
      }
    }其他{
      返回;
    }
  });
}

Note that the function AuthService.isAuthenticated() now returns a Promise, you will have to make a minor change to your authentication service to achieve this. Simply wrap your current logic like this:

app.factory('AuthService', function ($http, Data, $rootScope, $q) {
  var authService = {};

  authService.isAuthenticated = function () {
    return $q(function (resolve, reject) {
      Data.get('index.php/api/authentication/is_login').then(function (results) {
        if (results.uid) {
          $rootScope.authenticated = true;
          $rootScope.uid = results.uid;
          $rootScope.name = results.name;
          $rootScope.email = results.email;

          // Great, the user is authenticated, resolve the Promise
          resolve(results.uid);
        } else {
          // The user does not appear to be authenticated, reject the Promise
          reject();
        }
      });
    });
  };

  return authService;
});

I hope that this resolves your issue, Promises can be a pain, but they can also be a pretty powerful tool. There was a good thread on GitHub discussing a number of potential solutions around this issue that can be found here: https://github.com/angular-ui/ui-router/issues/1399.


这篇关于$ stateChangeStart从REST API获取数据之前运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 06:30