使用来自服务 Angularjs 的配置在 .运行() 中生成路由

Generate Routes in .run() with config from service Angularjs

我正在构建 routes/states 和基于用户有权查看的内容的菜单。我环顾四周并尝试了一些不同的东西,但我正在碰壁。每当调用 RoleService.validateRole() 时,RoleService Factory 中的 SessionService 对象为空。没有添加路线,应用程序实际上已经死了。为什么注入的工厂是空的,方法未定义。

这是按依赖项顺序开始的应用程序的简化布局。

在 app.run() 中,我将状态添加到应用程序而不是在配置中添加。

$stateProviderRef.state(value.stateName, state);

状态来自(工厂)AppConfig.getStates(),其中 returns 一个数组。

var states = AppConfig.getStates();

在 getStates() 中,我们验证每个路由的角色。

if(RoleService.validateRole(routes[i].role))

RoleService 依赖于 SessionService 并且 validateRole 函数执行此检查:

if(SessionService.currentUser.role === role)

SessionService 依赖于 AuthenticationService,它只是一个 returns 使用 $http(用户对象)的承诺的工厂。 SessionService.currentUser 是一个函数,它 .then()s 从 AuthenticationService 返回的承诺。

 return {
     currentUser: function(){
         AuthenticationService.then(function(result){
             return result;
         });
     }
 };

我不确定在不包含整个文件的情况下是否有更好的方法来解释代码。

基于plunker (mentioned in comment), I updated/cloned it to another, which is working

我。简单 - 当返回静态数据时(无 $http)

因为服务 SessonService 是这样定义的:

return {
    currentUser: function() {
    ...

我们不能称它为 属性:

...
return {
    validateRoleAdmin: function () {
        if (SessionService.currentUser.role === 'admin') {
        ...
    },

    validateRole: function (role) {
        if(SessionService.currentUser.role === role){
        ...

它是一个函数它必须作为函数调用currentUser():

return {
    validateRoleAdmin: function () {
        if (SessionService.currentUser().role === 'admin') {
        ...
    },

    validateRole: function (role) {
        if(SessionService.currentUser().role === role){
        ...

二.等待异步调用

adjusted example

接下来,如果我们在示例中创建服务 AuthenticationService 的静态结果:

angular.module('daedalus').factory('AuthenticationService', 
    function() {
      return {"idsid": "ad_jdschuma","role": "user","id": "33333"}
    }
)

我们不能指望会有一些方法:

currentUser: function() {
  //AuthenticationService.then(function(result) {
  //  return result;
  //});
  return AuthenticationService;
}

为了让它真正异步,我们可以将其替换为:

angular.module('daedalus').factory('AuthenticationService', 
    ['$timeout', function($timeout) {

    return {
      getData: function() {
        return $timeout(function() {
          return {
            "idsid": "ad_jdschuma",
            "role": "user",
            "id": "33333"
          }
        })
      }
    };     
 }])

然后甚至使用 .then() - 会话服务:

angular.module('daedalus').factory('SessionService', ['AuthenticationService', 
    function(AuthenticationService) {

        return {
              currentUser: function(){
                    return AuthenticationService
                      .getData()
                        .then(function(result){
                                return result;
                            });
                        }
        };
  }]
)

和角色服务:

  return {
    ...
    validateRole: function(route) {
      console.log('SessionService currentUser: ' + JSON.stringify(SessionService))
      return SessionService
        .currentUser()
        .then(function(userRole) {
          if (userRole.role === route.role) {
            return route;
          } else {
            return null;
          }
        })
    }

并在 appConfig 中就绪

getStates: function(){
    var items = [];
    var deffered = $q.defer();
    var validatedCount = routes.length;
    for(var i=0,len=routes.length; i<len; i++){
      var route = routes[i];
      RoleService
        .validateRole(route) 
        .then(function(route){
            if(route) {
                 items.push(route.stateConfig)
          }
          if(--validatedCount === 0 ){ // all processed
           deffered.resolve(items)
          }
        })
    }
    return deffered.promise;
}

我们可以在 运行:

AppConfig
  .getStates()
  .then(function(states) {console.log(states)
    angular.forEach(states, function(value, key) {
      var state = {
        "url": value.url,
        "templateUrl": value.templateUrl,
        "controller": value.controller
      };
      $stateProviderRef.state(value.stateName, state);


    });
    // Configures $urlRouter's listener *after* your custom listener            
    $urlRouter.sync();
  });

$urlRouter.listen();

检查一下here

方案二(async)的概念太.thenified()。我只是想表明一切正常。此处完全介绍了如何获取安全数据的更好方法:

Confusing $locationChangeSuccess and $stateChangeStart