角度路由异步授权 [英] Angular route async authorization

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

问题描述

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

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.

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

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.

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

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

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

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.

推荐答案

最简单的方法就是处理当前路由的resolve依赖,$routeChangeStart是一个很好的管理方法.这是一个例子.

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');
    }
  });
});

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

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

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

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