Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between application initializer and a service in ember?

Tags:

ember.js

As I am new to ember, I got confused between the application initializer and a service. To my knowledge, both of them was doing the same job and both have the lifetime of the application. Could anyone please explain the difference between them with a clear example?

like image 333
Raja.S.K Avatar asked Aug 28 '18 06:08

Raja.S.K


People also ask

What is a 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.

How can we inject a service ad hoc 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'; ).


2 Answers

Services can be injected into other areas of your app, where as application initializers cannot.

Services are useful for when you want to track app-level state, such as whether or not a sidebar is open/closed -- or if you want to manage the open/closed state of a modal -- or if you want to manage a websocket connection. Because Services are injectable, they allow the other areas of your application to interact with the services' functions, properties, etc.

Application Initializers are actually only run during boot, during the initialization of the _application. A common pattern here is if you want to inject a service into all routes or something.

Docs on Initializers: https://guides.emberjs.com/release/applications/initializers/

Docs on Services: https://guides.emberjs.com/release/applications/services/

like image 113
NullVoxPopuli Avatar answered Oct 12 '22 16:10

NullVoxPopuli


Application Initializer is a place where we initialize or Register or inject our new factory classes or any Services. And Both services and Application Initializer initialized class(factory) can share their states like a singleton to every routes they were used . Using applicationInstance.lookup() method we can even use any Application Initializer initialized class in which they were'nt injected initially when they were created and can share their states as well

like image 35
Magaesh Avatar answered Oct 12 '22 14:10

Magaesh