本文介绍了Angular 路由异步授权的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Angular 不提供任何关于路由的授权/访问权限(我说的是默认的 Angular 路由 1.x 而不是 beta 2.0 或 UI 路由).但我必须实施它.

我遇到的问题是我有一个服务调用服务器来提供这个信息并返回一个承诺.但是这个数据只获取一次,然后缓存在客户端,但还是需要获取一次.

我现在想处理 $routeChangeStart 事件,该事件检查下一条路由是否定义了特定属性 authorize: someRole.然后,此处理程序应使用我之前提到的服务获取该数据,并根据返回的数据采取相应的行动.

除了将 resolves 添加到我的所有路线之外还有什么想法吗?我可以以某种方式集中进行吗?对于所有适用的路线一次?

最终解决方案

在接受的答案的帮助下,我能够实现一个相当简单和集中的解决方案,它进行异步授权.单击此处查看其运行情况或检查其内部工作代码.

解决方案

最简单的方法是处理当前路由的解析依赖,而 $routeChangeStart 是管理这个的好地方.这是一个例子.

app.run(function ($rootScope, $location) {var unrestricted = ['', '/login'];$rootScope.$on('$routeChangeStart', function (e, to) {if (unrestricted.indexOf(to.originalPath) >= 0)返回;to.resolve = to.resolve ||{};//可以被路由定义覆盖to.resolve.auth = to.resolve.auth ||'认证服务';});$rootScope.$on('$routeChangeError', function (e, to, from, reason) {如果(reason.noAuth){//'to' 路径和参数也应该传递给登录$location.path('/登录');}});});

另一种选择是将 default 方法添加到 $routeProvider 并修补 $routeProvider.when 以从默认对象扩展路由定义.>

Angular doesn't provide any authorization/access permission on routing (I'm talking default Angular route 1.x and not beta 2.0 or UI route). But I do have to implement it.

The problem I'm having is that I have a service that calls server to provide this info and returns a promise. This data however is only obtained once and then cached on the client, but it still needs to be obtained once.

I would now like to handle $routeChangeStart event that checks whether next route defines a particular property authorize: someRole. This handler should then get that data using my previously mentioned service and act accordingly to returned data.

Any ideas beside adding resolves to all my routes? Can I do this centrally somehow? Once for all routes that apply?

Final solution

With the help of accepted answer I was able to implement a rather simple and centralized solution that does async authorization. Click here to see it in action or check its inner working code.

解决方案

The most simple way is to deal with current route's resolve dependencies, and $routeChangeStart is a good place to manage this. Here's an example.

app.run(function ($rootScope, $location) {
  var unrestricted = ['', '/login'];

  $rootScope.$on('$routeChangeStart', function (e, to) {
    if (unrestricted.indexOf(to.originalPath) >= 0)
      return;

    to.resolve = to.resolve || {};
    // can be overridden by route definition
    to.resolve.auth = to.resolve.auth || 'authService';
  });

  $rootScope.$on('$routeChangeError', function (e, to, from, reason) {
    if (reason.noAuth) {
      // 'to' path and params should be passed to login as well
      $location.path('/login');
    }
  });
});

Another option would be adding default method to $routeProvider and patching $routeProvider.when to extend route definition from default object.

这篇关于Angular 路由异步授权的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-07 04:47