作者:手机用户2702935840 | 来源:互联网 | 2023-05-19 08:36
ImtryingtoinjectanEmberserviceintoanEmberObjectbutkeepgettingthefollowingerror:我试图
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 on an
object without a container, ensure that the object was instantiated
via a container."
My code looks essentially something like the following:
我的代码基本上如下所示:
const Model = Ember.Object.extend({
store: Ember.inject.service(),
destroyRecord() {...},
serialize() {...},
deserialize() {...},
});
let newModel = Model.create();
newModel.get('store');
Note: it does work if I inject the service into a Controller, but not an object. Haven't had any luck trying to figure out how to register the Object with the Ember container.
注意:如果我将服务注入控制器而不是对象,那么它就可以工作。还没有任何运气试图弄清楚如何将对象注册到Ember容器中。
2 个解决方案
17
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.
它适用于灰烬。控制器,因为余烬控制对象的生命周期。简而言之,当Ember需要一个特定控制器的实例时,它会向容器请求一个实例,容器将提供这个实例,如果需要的话初始化它。
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:
这意味着对于依赖项注入,您需要通过容器获得一个新的模型实例。假设烬2.3是由于getOwner的缘故,而且这是烬应用程序中的某个地方:
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:
然后,打开生成的初始化器,假设文件在app/文件夹/模型中。js,把类似的:
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!
希望这是有帮助的!