Angular Services and Dependency Injection

A Service is...

  • for application logic
  • for data retrieval
  • consumed by components or other services

A Service is...

  • typically a class with a narrow, well-defined purpose
  • lazily instantiated
  • injected by an Injector
  • a Singleton (almost)

ng generate service book


import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root',
})
export class BookService {
}
            

@Injectable({
  provideIn: 'root'
})
export class BookService {
  private books: Book[] = [{...}, {...}];

  findAll(): Observable<Book[]> {
    return of(this.books);
  }
}
            
provideIn: 'root'

... registers the service in the root injector.

Component consumes a service making use of the Dependency Injection


@Component({...})
export class BookOverviewComponent{
  books$ = this.bookService.findAll();

  constructor(private bookService: BookService) {}
}
            

Summary

  • What is a service?
  • How can we create and use it?

Live Code Examples & Backup slides below

Live Code Examples

Backup slides

Following slides are not subject of the lecture.
Ask trainers in case of questions.

Overview with highlighted Services and Dependency Injection

Dependency Injection

Dependency injection is a way to supply a new instance of a class with the fully-formed dependencies it requires.

Most dependencies are services. Angular uses dependency injection to provide new components with the services they need.

Injector

When Angular creates a component, it asks an injector for the services that the component requires.

An injector keeps one instance per defined service

Each component instance has its own injector. The tree of components parallels the tree of injectors.

Providers

An injector can create a new service instance from a provider

A provider is a recipe for creating a service with configuration

You can register providers in modules or in components

In general, providers are added to the root module so that the same instance of a service is available everywhere

Injector Bubbling