Inject a service into an Ember Object [not an Ember Controller]

后端 未结 2 819
被撕碎了的回忆
被撕碎了的回忆 2021-02-14 00:21

I\'m trying to inject an Ember service into an Ember Object but keep getting the following error:

\"Assertion Failed: Attempting to lookup an injected property o         


        
2条回答
  •  离开以前
    2021-02-14 00:34

    It works for an Ember.Controller because Ember controls the lifecycle of the object. In short, when Ember needs an instance of a certain controller, it asks the container for one, and the container will provide the instance, initializing if necessary.

    What this implies is that for dependency injection to work, you would need to get a new instance of Model through the container. Assuming Ember 2.3 because of getOwner, and that this is somewhere inside the Ember application:

    let owner = Ember.getOwner(this);
    let newModel = owner.lookup('object:model');
    newmodel.get('store');
    

    You can consult the lookup documentation here.

    But how to register? Use an application initializer:

    $ ember generate initializer register-model
    

    Then, open up the generated initializer and, assuming that your file is in app/folder/model.js, put something like:

    import Model from 'app-name/folder/model';
    
    export function initialize(application) {
      application.register('object:model', Model);
    }
    
    export default {
      name: 'register-model',
      initialize
    };
    

    You can consult the register documentation here.

    Hope this is helpful!

提交回复
热议问题