简体   繁体   中英

angularjs route to resolve

I have a big number of angularjs routes in my app. I would like to set access to these route based on some user permission levels.

angular.module('myApp').run(['$rootScope', 'someAuthFactory', function($rootScope, someAuthFactory) {
$rootScope.$on('$stateChangeStart', function (event, toState) {
            $rootScope.permissions = someAuthFactory.getPermssionLevels();
            $rootScope.specialRights = $rootScope.permissions.indexOf('superRole') > -1;
...

and here is one of my routes:

.state("dashboard.overview", {
    url: "/dashboard",
    templateUrl: "app/dashboard.html",
    resolve: {
        roles: ['rootScope', function (rootScope) {
            return $rootScope.specialRights;}]
        },

so this code works, but if i want to add this:

resolve: {
        roles: ['rootScope', function (rootScope) {
            return $rootScope.specialRights;}]
        }

to every route, it is gonna be duplicate code, or if I want to lookup some other role, it is gonna be boring. Could we make the resolve part much smaller and much cleaner?

create a variable in config function on top of the routes like this

var resolveRoles = ['rootScope', function (rootScope) {
   return $rootScope.specialRights;}]
}

and use it in every route like this,

   .state("dashboard.overview", {
        url: "/dashboard",
        templateUrl: "app/dashboard.html",
        resolve: {
            roles: resolveRoles
        },
    });

You can create a service/factory, which shares $rootScope.specialRights. Just init $rootScope.specialRights in the service in the first resolve of your route eg

 .state("dashboard", {
    url: ...
    templateUrl: ...
    resolve: {
        roles: ['rootScope', function (rootScope) {
                YourServiceOrFactory.setSpecialRights($rootScope.specialRights);
                return $rootScope.specialRights
     }]
},

And there where you need it

  YourServiceOrFactory.getSpecialRights()

It does not have to be in other resolves, just in your controller of your route or in your directive/component. Much cleaner and performanter than multiple resovles.

Since you're already setting this property in $rootScope , it is an overkill to use resolve in all of your routes, just to get a variable value, and of course, resolve is not designed for such purposes.

Instead, just inject the $rootScope in your controller and use $rootScope.specialRights in the controller.

Example:

In your controller, service, directive, or component, you can inject the $rootScope like this:

angular.module('your_module')
  .controller('your_controller', ['$rootScope', function($rootScope) {
    // Access $rootScope.permissions or $rootScope.specialRights here
  }];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM