Specify Providers For Services
Specify Providers For Services
● }
● Configuring providedIn: 'root' means that above service instance will be created by root
injector by using service constructor. If there are parameters in constructor, that
will be provided by the injector. The service configured with providedIn: 'root' will be
available for dependency injection for all components and services in the
application. @Injectable() decorator can also configure providers using useClass, useExisting,
useValueand useFactory properties. Find some examples.
●
● useExisting Example:
● import { Injectable } from '@angular/core';
● import { Computer } from './computer';
● import { LaptopService } from './laptop.service';
●
● @Injectable({
● providedIn: 'root',
● useExisting: LaptopService
● })
● export class DesktopService implements Computer {
● ------
● }
●
● useFactory Example:
● import { Injectable } from '@angular/core';
● import { BookService } from './book.service'
●
● @Injectable({
● providedIn: 'root',
● useFactory: (bookService: BookService) =>
● new PreferredBookService(bookService),
● deps: [ BookService ]
● })
● export class PreferredBookService {
● constructor(private bookService: BookService) {}
● ------
● }