InjectionToken
This is the documentation for Angular 6.
You can switch to the latest version Angular 10.
You can switch to the latest version Angular 10.
Use an InjectionToken
whenever the type you are injecting is not reified (does not have a runtime representation) such as when injecting an interface, callable type, array or parametrized type.
InjectionToken
is parameterized on T
which is the type of object which will be returned by the Injector
. This provides additional level of type safety.
interface MyInterface {...}
var myInterface = injector.get(new InjectionToken<MyInterface>('SomeToken'));
// myInterface is inferred to be MyInterface.
Example
Plain InjectionToken
:
const BASE_URL = new InjectionToken<string>('BaseUrl');
const injector =
Injector.create({providers: [{provide: BASE_URL, useValue: 'http://localhost'}]});
const url = injector.get(BASE_URL);
// here `url` is inferred to be `string` because `BASE_URL` is `InjectionToken<string>`.
expect(url).toBe('http://localhost');
Tree-shakable InjectionToken
:
class MyService {
constructor(readonly myDep: MyDep) {}
}
const MY_SERVICE_TOKEN = new InjectionToken<MyService>('Manually constructed MyService', {
providedIn: 'root',
factory: () => new MyService(inject(MyDep)),
});
const instance = injector.get(MY_SERVICE_TOKEN);
expect(instance instanceof MyService).toBeTruthy();
expect(instance.myDep instanceof MyDep).toBeTruthy();
Costructor parameters
InjectionToken<T>(
_desc: string,
options?: { providedIn?: Type<any> | 'root' | null; factory: () => T; },
);
_desc
#
_desc: string
options
#
options?: { providedIn?: Type<any> | 'root' | null; factory: () => T; }