Service
- A service is typically a class with a narrow, well-defined purpose. It should do something specific and do it well.
- Every module is defined with a @Injectable decorator.
- Then you can inject a service into a component, giving the component access to that service class.
Cli: ng g s <service name>
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class TestServiceService {
constructor() { }
}
Definition:
- Dependencies -- services which have a functionality, but not limited to services
- Functionality -- Something needed by components and directives in the application
- Injection -- A mechanism provided by Angular to provide services to components and directives
Dependency
An Angular service declared with an @Injectable decorator.
@Injectable({
providedIn: 'root'
})
Providing
Register provider at a specific level to limit the service availability.
Root level
This allows the service to be have global availability.
To do this, you register in the service class itself:
@Injectable({
providedIn: 'root',
})
Module level
This allows the service to be available in a particular module.
To do this, you register in the module class:
@NgModule({
providers: [
BackendService,
Logger
],
…
})
Component level
This allows the service to be available in a particular component.
To do this, you register in the component class:
@Component({
selector: 'app-hero-list',
templateUrl: './hero-list.component.html',
providers: [ HeroService ]
})
Injection
- In the component needing the service
- Import the service class
- Declare an instance of the class
- Boom! the service is now usable in the component!
import { XXXService } from '.....';
/* ... */
constructor(private xxxService:XXXService) { }
Under the hood injection machanism:
- XXXService is registered as a component dependency
- Angular search the injector for existing service instance
- if exist, return and inject that instance
- if not, use provider (service class) to create instance then inject