Pass Parameters to Angular 10 Service with @Inject
In this post we will give you information about Pass Parameters to Angular 10 Service with @Inject. Hear we will give you detail about Pass Parameters to Angular 10 Service with @InjectAnd how to use it also give you demo for it if it is necessary.
You can pass parameters to Angular 10 (and previous versions) services, using the @Inject
decorator to create injection tokens. It allows you to pass parameters to the service via the Angular dependency injector.
Injection tokens allow you to inject any values that don’t have a runtime representation such as TypeScript interfaces which don’t have JavaScript equivalents.
Angular Service and Component Example
Let’s suppose we have a service which needs a parameter as follows:
import{Inject,Injectable}from'@angular/core';@Injectable({providedIn:'root'})exportclassMyService{constructor(privateparam:string){}}
This is an example component that would make use of the service:
import{Component}from'@angular/core';@Component({selector:'app-my',template:'<div"></div>',})exportclassMyComponent{constructor(){}}
Now, we need to pass in the param
to the service.
Creating an Injection Token with @Inject
We can create an injection token from the parameter using the @Inject
decorator:
import{Inject,Injectable}from'@angular/core';@Injectable({providedIn:'root'})exportclassMyService{constructor(@Inject('param')privateparam:string){}}
Providing the Injection Toekn
Next, we provide the token to the service using the component’s providers
array as follows:
import{Component}from'@angular/core';@Component({selector:'app-my',template:'<div></div>',providers:[{provide:'param',useValue:'container'},]})exportclassMyComponent{constructor(privatemyService:MyService){}}
Now we have passed a parameter to our Angular 10 service.
Hope this code and post will helped you for implement Pass Parameters to Angular 10 Service with @Inject. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve us. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs