AngularJS:如何对我的应用程序的所有路由使用一种解析 [英] AngularJS : How to use one resolve for all the routes of my application

查看:55
本文介绍了AngularJS:如何对我的应用程序的所有路由使用一种解析的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想解决为我的应用程序所有页面加载当前用户的承诺. 目前,我在每个路由的$routeProvider.when()中都重复执行该解析.

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() of my routes.

  $routeProvider.when('/users/edit/:userId', {
  templateUrl: 'app/app/assets/partials/user-edit.html', 
  controller: 'UserEditController',
  resolve:{  
    'currentUser':function( UserService){            
        return UserService.getCurrentUser();
      }
  }
  });  

  $routeProvider.when('/staff_profil/edit', {
  templateUrl: 'app/app/assets/partials/profil-edit.html', 
  controller: 'ProfilEditController',
  resolve:{  
    'currentUser':function( UserService){            
        return UserService.getCurrentUser();
      }
  }
 });

我的目标是解决所有路由的当前用户,而无需重复.

My goal is to resolve my current user for all the routes without repetition.

推荐答案

您始终可以将现有的when方法包装在 $routeProvider 和您自己的实现.

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

   }]);

您可能想在其中添加一些错误检查,并使用类似下划线defaults 的方法.仅覆盖现有的resolve属性,但至少可以通过这种方式,可以确保所有路由都具有所需的内容.

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.

这篇关于AngularJS:如何对我的应用程序的所有路由使用一种解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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