A friend of mine recently had a job interview with a top UK firm , looking for Angular developer .I could remember him calling to tell me, he didn't do so well in the interview .So I ask him to tell me the questions that was asked.This particular question got my attention.
*What is Token injection in Angular *
The Injection Token allows creating token that allows the injection of values that don't have a runtime representation.
Now the above is too complex for me to understand so let break it down
Imagine you working on a project with has multiple base-url
This baseUrl above contains series of endpoint nested under them like
- readOneBread
- readAllBread
The best way to load this individual api without conflict is by using the angular token injection.
To create a token injection use the following
- create a file called
app.config.ts
import {InjectionToken} from "@angular/core"
export const CAT_URL = new InjectionToken<string>(_desc:'cat api')
export const DOG_URL = new InjectionToken<string>(_desc:'dog api')
- Register the token in the provider of your module
provider:[{
provide:CAT_URL,
useValue:'http://cat.api/'
},
{
provide:DOG_URL,
useValue:'http://dog.api/'
},
]
- Finally to access this in our services
Constructor(private client:HttpClient,@inject(CAT_URL)private cat_url:string ){
}
getAllBread(){
this.client.get(this.cat_url+'readAllBread')
}
Thanks for reading.
Top comments (0)