Appearance
Custom provider in @NgModule and @Component
In Angular, we can provide a custom provider by using the provide property in the @NgModule decorator or the providers property in the @Component decorator. This allows us to specify a custom token and the corresponding provider value.
Here's how we can provide a custom provider in Angular:
- Import the necessary dependencies:
typescript
import { NgModule } from '@angular/core';
import { MyCustomService } from './my-custom.service';- Create a custom token for your provider. This token can be a string or an instance of the
InjectionTokenclass from@angular/core. For example:
typescript
import { InjectionToken } from '@angular/core';
export const MY_CUSTOM_TOKEN = new InjectionToken<string>('MyCustomToken');- Define your custom provider using the
provideproperty within the@NgModuledecorator or theprovidersproperty within the@Componentdecorator. Here's an example of providing the custom token and associating it with your custom service:
typescript
@NgModule({
providers: [
{ provide: MY_CUSTOM_TOKEN, useClass: MyCustomService }
]
})
export class AppModule { }- In the component or service where we want to use the provided value, inject the custom provider using the
@Injectdecorator and the custom token. For example:
typescript
import { Component, Inject } from '@angular/core';
import { MY_CUSTOM_TOKEN } from './my-custom.token';
@Component({
selector: 'app-my-component',
template: '...',
providers: [{ provide: MY_CUSTOM_TOKEN, useClass: MyCustomService }]
})
export class MyComponent {
constructor(@Inject(MY_CUSTOM_TOKEN) private customService: MyCustomService) {
// Use the custom service...
}
}In the example above, the MyCustomService is provided using the custom token MY_CUSTOM_TOKEN at both the module level and the component level. This allows us to provide a different instance of the service at the component level if needed.