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.
$ ember g service session
import Service from '@ember/service';
import { computed } from '@ember/object';
export default Service.extend({
fetchStuff () {
// this could be async
return [];
}
});
import { inject as service } from '@ember/service';
session: service()
// available in this class as this.get('session');
Or
userSession: service('session')
// now available in this class as this.get('userSession');
// app/initializers/session.js
export function initialize(application) {
application.inject('route', 'session', 'service:session');
}
export default {
initialize
};
// now available in all routes as this.get('session');
$ ember g component user-profile
// app/components/user-profile/component.js
import Component from '@ember/component';
import { computed } from '@ember/object';
export default Component.extend({
tagName: 'h2',
classNames: [ 'user-profile-component' ],
greeting: computed('firstName', 'lastName', function () {
return `Hello, ${this.get('firstName')} ${this.get('lastName')}!`;
})
});
{{!-- app/components/user-profile/template.hbs --}}
{{greeting}}
{{!-- some template somewhere --}}
{{user-profile firstName="Mike" lastName="Juniper"}}
<!-- renders -->
<h2 class="user-profile-component">Hello, Mike Juniper!</h2>
this._super(...arguments);
this.$(...);
Child components do not mutate data they do not own.
Instead they: