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

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

问题描述

角不提供任何路由授权/访问权限(我说的是缺省路由角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 事件授权:someRole 。然后,该处理程序应使用我的previously提到的服务和行为据此返回的数据获得这些数据。

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.

旁边加任何想法的解析<​​/ em>的我所有的路线?我能做到这一点集中不知何故?一旦所有路由适用?

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

通过接受的答案的帮助下,我能够实现一个非常简单和集中的解决方案,它异步授权。 点击这里看到它在操作或检查其内部工作code

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.

推荐答案

最简单的办法就是处理当前路线的决心依赖性和 $ 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');
    }
  });
});

另一个选择是加入默认方法 $ routeProvider 和修补 $ routeProvider。当从默认的对象扩展路由定义。

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

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

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