AngularJS : How to use one resolve for all the routes of my application

前端 未结 6 984
陌清茗
陌清茗 2020-11-30 00:53

I would like to resolve the promise that loads the current user for all the pages of my application. Currently I repeat the resolve in every $routeProvider.when()

6条回答
  •  一向
    一向 (楼主)
    2020-11-30 01:04

    You could always wrap the existing when method on the $routeProvider with your own implementation.

    var myModule = angular.module('myModule', ['ngRoute'])
       .config(['$routeProvider', function($routeProvider){
    
          var originalWhen = $routeProvider.when;
    
          $routeProvider.when = function(path, route){
    
             route.resolve = {
                'currentUser':function( UserService){            
                  return UserService.getCurrentUser();
                }
             };
    
             return originalWhen(path, route);
          };   
    
       }]);
    

    You probably want to add some error checking in there, and use something like underscores defaults method instead of just overwriting the existing resolve property, but at least this way you can guarantee all your routes will have what you want.

    It's also easy enough to wrap this up into a helper method.

提交回复
热议问题