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

查看:19
本文介绍了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.

推荐答案

你总是可以在 $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);
      };   

   }]);

您可能想在那里添加一些错误检查,并使用类似 underscores defaults 方法而不是仅仅覆盖现有的解析属性,但至少这样你可以保证你的所有路由都有你想要的.

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天全站免登陆