Angular services
testYourself Angular819
Angular services are classes that store logic not strictly related to the view. This logic can be shared between the various components.
Create a service
To create a new service in Angular, we just create a new class and decorate it with the @Injectable
decorator.
import { Injectable } from '@angular/core';
@Injectable()
export class ProductsService {}
The @Injectable d
ecorator marks a class as available to be provided and injected as a dependency.
Before we inject a service we have to add it to the providers
' array.
import { NgModule } from '@angular/core';
import { ProductsService } from './products.service';
@NgModule({
providers: [
ProductsService
]
})
export class AppModule {}
A providers
property is used to register a list of dependency-injection providers.
By default, if Angular cannot find a dependency it throws an error.
Service's dependencies
The services may depend on other services, both those provided by Angular and custom:
import { Injectable } from "@angular/core";
import { HttpClient } from "@angular/common/http";
import { Logger } from "./logger.service";
@Injectable({
providedIn: 'root'
})
export class UserService {
constructor(
private httpClient: HttpClient,
private logger: Logger
) {
}
}
Component's providers
You can register providers in modules or in components. No matter if we want to register a service in the module or in the component, in both cases we add it to the providers
array.
When you add providers to the root module, the same instance of a service is available to all components in the app. Angular registers these providers with the NgModule injector.
@NgModule({
providers: [
ProductsService
]
})
export class AppModule { }
When you register a provider at the component level, you get a new instance of the service with each new instance of that component.
@Component({
selector: "main",
templateUrl: "./main.html",
providers: [
ProductsService
]
})
export class MainComponent { }
That service is available via the ElementInjector
at that component instance. It may also be visible at child component/directives.