AngularJS UI Router using resolved dependency in factory / service

后端 未结 3 1307
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-09 15:04

I have a UI Router defined something like this (trimmed for simplicity):

    $stateProvider
        .state(\'someState\', {
            resolve: {
                       


        
3条回答
  •  忘了有多久
    2021-02-09 15:19

    Do resolves only work on controllers?

    Yes, resolves only work on controllers.

    And if that is the case, how can I use a resolve inside a factory / service?

    Remember that factories and services return singleton objects, i.e. the first time a factory is injected into a controller, it runs any instantiation code you provide and creates an object, and then any subsequent times that factory is instantiated, that same object is returned.

    In other words:

    angular.module('someModule')
    .factory( 'SomeFactory' , function () {
      // this code only runs once
      object = {}
      object.now = Date.now();
      return object
    );
    

    SomeFactory.now will be the current time the first time the factory is injected into a controller, but it not update on subsequent usage.

    As such, the concept of resolve for a factory doesn't really make sense. If you want to have a service that does something dynamically (which is obviously very common), you need to put the logic inside functions on the singleton.

    For example, in the code sample you gave, your factory depended on a model. One approach would be to inject the model into the controller using the resolve method you've already got set up, then expose a method on the singleton that accepts a model and does what you need to do, like so:

    angular.module('someModule')
    .factory( 'SomeFactory', function () {
      return {
        doSomethingWithModel: function (model) {
          $http.post('wherever', model);
      }
    });
    .controller('SomeController', function (SomeFactory, model) {
      SomeFactory.doSomethingWithModel(model);
    });
    

    Alternatively, if you don't need the resolved value in the controller at all, don't put it directly in a resolve, instead put the resolve logic into a method on the service's singleton and call that method inside the resolve, passing the result to the controller.

    It's hard to be more detailed with abstract conversation, so if you need further pointers then provide a specific use-case.

提交回复
热议问题