Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ember.js

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.

like image 872
James Conkling Avatar asked Jan 24 '16 00:01

James Conkling


People also ask

How can we inject a service adhoc In an ember object?

Ad Hoc Injections Dependency injections can also be declared directly on Ember classes using inject . Currently, inject supports injecting controllers (via import { inject } from '@ember/controller'; ) and services (via import { inject } from '@ember/service'; ).

What is service in Ember?

A Service is an Ember object that lives for the duration of the application, and can be made available in different parts of your application. Services are useful for features that require shared state or persistent connections. Example uses of services might include: User/session authentication. Geolocation.


1 Answers

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!

like image 108
locks Avatar answered Sep 27 '22 17:09

locks