W3cubDocs

/Angular 4 TypeScript

InjectionToken

Stable Class

Class Overview

class InjectionToken extends OpaqueToken {
  constructor(desc: string)
  
  
  toString() : string
}

Class 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 parametrize 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 injector: Injector =
    ReflectiveInjector.resolveAndCreate([{provide: 'validToken', useValue: 'Value'}]);
expect(injector.get('validToken')).toEqual('Value');
expect(() => injector.get('invalidToken')).toThrowError();
expect(injector.get('invalidToken', 'notFound')).toEqual('notFound');

Constructor

constructor(desc: string)

Class Details

toString() : string

exported from core/index, defined in core/src/di/injection_token.ts

© 2010–2017 Google, Inc.
Licensed under the Creative Commons Attribution License 4.0.
https://angular.io/docs/ts/latest/api/core/index/InjectionToken-class.html