Services in Ember are scoped to the app as a whole and are singletons. Sometimes you don't want that. :) This addon provides ephemeral route-based services.
MIT License
Eliminate Prop-Drilling by Providing Ephemeral Services based on the route!
Q: How is this different from Ember's Services?
A: Three differences:
Q: Do the contextual services need to live in a specific location?
A: No, but co-location is highly encouraged. One of the main benefits to using contextual services over app-wide services is that usage can be reflected by the location of the file.
ember install @nullvoxpopuli/ember-contextual-services
All ContextualServices are classes that can hold any state or perform any action. They could represent specific interfaces to APIs, or a way of accessing data loaded from ember-data from deep within the route's component tree.
NOTE: all of these examples are available for viewing in the tests/dummy
folder.
in routes/wherever/-contexts/local-service.js;
import { ContextualService } from '@nullvoxpopuli/ember-contextual-services';
import { inject as service } from '@ember/service';
import { tracked } from '@glimmer/tracking';
import { action } from '@ember/object';
export class LocalService extends ContextualService {
@service router;
@tracked foo = 0;
@action incrementFoo() {
this.foo++;
}
}
in routes/wherever/some-route.js
import Route from '@ember/routing/route';
import { withContextualServices } from '@nullvoxpopuli/ember-contextual-services';
import { LocalService } from './-contexts/local-service';
@withContextualServices(LocalService)
export default class SomeRoute extends Route {
}
or if you want to utilize the route's model hook for data-loading, you could do:
@withContextualServices(PersonService)
export default class SomeRoute extends Route {
@context(PersonService) personService;
async model() {
let response = await fetch('https://swapi.co/api/people/1/');
let json = await response.json();
this.personService.data = json;
}
}
and finally, in a component that is rendered by your route's template or a tree of components fromy our route's template,
import Component from '@glimmer/component';
import { context } from '@nullvoxpopuli/ember-contextual-services';
import { LocalService } from 'my-app/routes/whatever/-contexts/local-service';
export default class ServiceConsumer extends Component {
@context(LocalService) localService;
}
See the Contributing guide for details.
This project is licensed under the MIT License.