Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
994 views
in Technique[技术] by (71.8m points)

angularjs - Angular route async authorization

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...