On this page
InjectionToken
class
npm Package | @angular/core |
---|---|
Module | import { InjectionToken } from '@angular/core'; |
Source | core/src/di/injection_token.ts |
Overview
class InjectionToken<T> extends OpaqueToken {
constructor(desc: string)
toString(): string
// inherited from core/OpaqueToken
protected _desc: string
toString(): string
}
Description
Creates a token that can be used in a DI Provider.
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
const BASE_URL = new InjectionToken<string>('BaseUrl');
const injector =
ReflectiveInjector.resolveAndCreate([{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');
Constructor
constructor(desc: string)
Members
toString(): string
© 2010–2017 Google, Inc.
Licensed under the Creative Commons Attribution License 4.0.
https://v4.angular.io/api/core/InjectionToken