本文介绍了angular-ui 路由器——继承已解析的 NAMED 依赖项的依赖项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据文档中的示例,子状态将从父状态继承解析的依赖项.此外,您可以在通过将键注入子状态来实例化子项之前解决父依赖项的承诺.

Per the example in the documentation, child states will inherit resolved dependencies from parent states. Furthermore, you can have promises for parent dependencies be resolved before children are instantiated by injecting keys into child states.

查看文档中的示例:

$stateProvider.state('parent', {
      resolve:{
         resA:  function(){
            return {'value': 'A'};
         }
      },
      controller: function($scope, resA){
          $scope.resA = resA.value;
      }
   })
   .state('parent.child', {
      resolve:{
         resB: function(resA){
            return {'value': resA.value + 'B'};
         }
      },
      controller: function($scope, resA, resB){
          $scope.resA2 = resA.value;
          $scope.resB = resB.value;
      }

但是,如果依赖项是 NAMED,而不是函数,您将如何执行此操作.例如,参见粗体部分:

However, how do you do this if the dependency is NAMED, not a function. For example, see bolded part:

$stateProvider.state('parent', {
      resolve:{
         resA:  'ServiceA'
         }
      },
      controller: function($scope, ServiceA){
          $scope.ServiceA = ServiceA.value;
      }
   })
   .state('parent.child', {
      resolve:{
         ServiceB: ServiceB
         }
      },
      controller: function($scope, ServiceA, ServiceB){
      }

我不知道如何让 ServiceB 在实例化之前等待 ServiceA 首先实例化.

I can't figure out how to make ServiceB wait for ServiceA to first be instantiated before instantiating.

我尝试将ServiceA"作为 ServiceB 的依赖项,但这不起作用.

I tried putting 'ServiceA' as a dependency for ServiceB, but that doesn't work.

在此先感谢您的帮助.

推荐答案

这与 ui-router 无关.您只想知道如何在另一个服务之前实例化一个服务.答案是您不能,并且需要更改您的设计.

This has nothing to do with ui-router. What you simply want to know is how do you instantiate one service before another. The answer is that you can't, and need to change your design.

如果ServiceA 中有些东西需要完成以便ServiceB 可以使用它,那么你应该在ServiceA 中使用promise.例如:

If there is something inside ServiceA that needs to complete so that ServiceB can consume it, then you should use promises inside ServiceA. For example:

.factory('ServiceA', function($q){
    var deferred = $q.defer();       

    // Do some kind of work here and when complete, run deferred.resolve();

    return {
        myPromise: function() { return deferred.promise; }
    };
});

然后在ServiceB中消费:

.factory('ServiceB', function(ServiceA){
    ServiceA.myPromise().then(function(){
        // This will run after your ServiceA work has completed
    });
});

阅读 $q 文档了解更多信息:link这里

Read the $q documentation for more info: link here

这篇关于angular-ui 路由器——继承已解析的 NAMED 依赖项的依赖项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-17 11:59