Services

  • A service is generally just a class
  • Should only do one specific thing
  • Takes the burden of business logic out of Components
  • It is considered best practice to always use @Injectable so that metadata is generated correctly
  • By using the provideIn: 'root' property, we are specifying that Angular should provide that service to the root injector

Services are used to share data and functionality between different components. A component should use services for tasks that don't involve the view or application logic.

Services can depend on other services. For example, here's a HeroService that depends on the Logger service, and also uses BackendService to get heroes. That service in turn might depend on the HttpClient service to fetch heroes asynchronously from a server.

export class HeroService {
  private heroes: Hero[] = [];

  constructor(
    private backend: BackendService,
    private logger: Logger) { }

  getHeroes() {
    this.backend.getAll(Hero).then( (heroes: Hero[]) => {
      this.logger.log(`Fetched ${heroes.length} heroes.`);
      this.heroes.push(...heroes); // fill cache
    });
    return this.heroes;
  }
}

A service can be provided to different components using Dependency Injection.

A service can be generated by using:

Generate Service

ng generate service my-service
ng g s my-service

The Injectable decorator defines a class as a service in Angular and allows Angular to inject it into a Components as a dependency.

Providing services

You must register at least one provider of any service you are going to use. The provider can be part of the service's own metadata, making that service available everywhere, or you can register providers with specific modules or components. You register providers in the metadata of the service (in the @Injectable() decorator), or in the @NgModule() or @Component() metadata


Backlinks