In order to create a single instance of service in the Angular application we need to specify providedIn attribute as root of @Injectable decorator.
When we use root then the injectable will be registered as a singleton in the application and needn't add it to the providers of any specific module we wish to use.
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root',-->specifies that Angular should provide the service in the root injector.
})
export class ProductService {
}
It's also possible to specify that a service should be provided in a particular @NgModule
import { Injectable } from '@angular/core';
import { ProductModule } from './product.module';
@Injectable({
providedIn: ProductModule, -->specifies that Angular should provide the service in the User Module only.
})
})
export class ProductService {
}
OR
We can also declare a provider for the service within the module:
import { NgModule } from '@angular/core';
import { ProductService } from './product.service';
@NgModule({
providers: [ProductService],
})
export class ProductModule {
}
Comments
Post a Comment