feat(core): Add type information to injector.get() (#13785)

- Introduce `InjectionToken<T>` which is a parameterized and type-safe
  version of `OpaqueToken`.

DEPRECATION:
- `OpaqueToken` is now deprecated, use `InjectionToken<T>` instead.
- `Injector.get(token: any, notFoundValue?: any): any` is now deprecated
  use the same method which is now overloaded as
  `Injector.get<T>(token: Type<T>|InjectionToken<T>, notFoundValue?: T): T;`.

Migration
- Replace `OpaqueToken` with `InjectionToken<?>` and parameterize it.
- Migrate your code to only use `Type<?>` or `InjectionToken<?>` as
  injection tokens. Using other tokens will not be supported in the
  future.

BREAKING CHANGE:
- Because `injector.get()` is now parameterize it is possible that code
  which used to work no longer type checks. Example would be if one
  injects `Foo` but configures it as `{provide: Foo, useClass: MockFoo}`.
  The injection instance will be that of `MockFoo` but the type will be
  `Foo` instead of `any` as in the past. This means that it was possible
  to call a method on `MockFoo` in the past which now will fail type
  check. See this example:

```
class Foo {}
class MockFoo extends Foo {
  setupMock();
}

var PROVIDERS = [
  {provide: Foo, useClass: MockFoo}
];

...

function myTest(injector: Injector) {
  var foo = injector.get(Foo);
  // This line used to work since `foo` used to be `any` before this
  // change, it will now be `Foo`, and `Foo` does not have `setUpMock()`.
  // The fix is to downcast: `injector.get(Foo) as MockFoo`.
  foo.setUpMock();
}
```

PR Close #13785
This commit is contained in:
Miško Hevery
2017-01-03 16:54:46 -08:00
committed by Miško Hevery
parent 6d1f1a43bb
commit d169c2434e
59 changed files with 255 additions and 175 deletions

View File

@ -8,14 +8,14 @@
import {isPromise} from '../src/util/lang';
import {Inject, Injectable, OpaqueToken, Optional} from './di';
import {Inject, Injectable, InjectionToken, Optional} from './di';
/**
* A function that will be executed when an application is initialized.
* @experimental
*/
export const APP_INITIALIZER: any = new OpaqueToken('Application Initializer');
export const APP_INITIALIZER = new InjectionToken<Array<() => void>>('Application Initializer');
/**
* A class that reflects the state of running {@link APP_INITIALIZER}s.

View File

@ -16,7 +16,7 @@ import {ApplicationInitStatus} from './application_init';
import {APP_BOOTSTRAP_LISTENER, PLATFORM_INITIALIZER} from './application_tokens';
import {ChangeDetectorRef} from './change_detection/change_detector_ref';
import {Console} from './console';
import {Injectable, Injector, OpaqueToken, Optional, Provider, ReflectiveInjector} from './di';
import {Injectable, InjectionToken, Injector, Optional, Provider, ReflectiveInjector} from './di';
import {CompilerFactory, CompilerOptions} from './linker/compiler';
import {ComponentFactory, ComponentRef} from './linker/component_factory';
import {ComponentFactoryResolver} from './linker/component_factory_resolver';
@ -83,7 +83,7 @@ export function createPlatform(injector: Injector): PlatformRef {
'There can be only one platform. Destroy the previous one to create a new one.');
}
_platform = injector.get(PlatformRef);
const inits: Function[] = <Function[]>injector.get(PLATFORM_INITIALIZER, null);
const inits = injector.get(PLATFORM_INITIALIZER, null);
if (inits) inits.forEach(init => init());
return _platform;
}
@ -96,7 +96,7 @@ export function createPlatform(injector: Injector): PlatformRef {
export function createPlatformFactory(
parentPlatformFactory: (extraProviders?: Provider[]) => PlatformRef, name: string,
providers: Provider[] = []): (extraProviders?: Provider[]) => PlatformRef {
const marker = new OpaqueToken(`Platform: ${name}`);
const marker = new InjectionToken(`Platform: ${name}`);
return (extraProviders: Provider[] = []) => {
if (!getPlatform()) {
if (parentPlatformFactory) {
@ -413,7 +413,7 @@ export class ApplicationRef_ extends ApplicationRef {
/** @internal */
static _tickScope: WtfScopeFn = wtfCreateScope('ApplicationRef#tick()');
private _bootstrapListeners: Function[] = [];
private _bootstrapListeners: ((compRef: ComponentRef<any>) => void)[] = [];
private _rootComponents: ComponentRef<any>[] = [];
private _rootComponentTypes: Type<any>[] = [];
private _views: AppView<any>[] = [];
@ -480,8 +480,7 @@ export class ApplicationRef_ extends ApplicationRef {
this._rootComponents.push(componentRef);
// Get the listeners lazily to prevent DI cycles.
const listeners =
<((compRef: ComponentRef<any>) => void)[]>this._injector.get(APP_BOOTSTRAP_LISTENER, [])
.concat(this._bootstrapListeners);
this._injector.get(APP_BOOTSTRAP_LISTENER, []).concat(this._bootstrapListeners);
listeners.forEach((listener) => listener(componentRef));
}

View File

@ -6,7 +6,8 @@
* found in the LICENSE file at https://angular.io/license
*/
import {OpaqueToken} from './di';
import {InjectionToken} from './di';
import {ComponentRef} from './linker/component_factory';
/**
@ -19,7 +20,7 @@ import {OpaqueToken} from './di';
* using this token.
* @experimental
*/
export const APP_ID: any = new OpaqueToken('AppId');
export const APP_ID = new InjectionToken<string>('AppId');
export function _appIdRandomProviderFactory() {
return `${_randomChar()}${_randomChar()}${_randomChar()}`;
@ -43,7 +44,7 @@ function _randomChar(): string {
* A function that will be executed when a platform is initialized.
* @experimental
*/
export const PLATFORM_INITIALIZER: any = new OpaqueToken('Platform Initializer');
export const PLATFORM_INITIALIZER = new InjectionToken<Array<() => void>>('Platform Initializer');
/**
* All callbacks provided via this token will be called for every component that is bootstrapped.
@ -53,10 +54,11 @@ export const PLATFORM_INITIALIZER: any = new OpaqueToken('Platform Initializer')
*
* @experimental
*/
export const APP_BOOTSTRAP_LISTENER = new OpaqueToken('appBootstrapListener');
export const APP_BOOTSTRAP_LISTENER =
new InjectionToken<Array<(compRef: ComponentRef<any>) => void>>('appBootstrapListener');
/**
* A token which indicates the root directory of the application
* @experimental
*/
export const PACKAGE_ROOT_URL: any = new OpaqueToken('Application Packages Root URL');
export const PACKAGE_ROOT_URL = new InjectionToken<string>('Application Packages Root URL');

View File

@ -21,4 +21,4 @@ export {ReflectiveInjector} from './di/reflective_injector';
export {Provider, TypeProvider, ValueProvider, ClassProvider, ExistingProvider, FactoryProvider} from './di/provider';
export {ResolvedReflectiveFactory, ResolvedReflectiveProvider} from './di/reflective_provider';
export {ReflectiveKey} from './di/reflective_key';
export {OpaqueToken} from './di/opaque_token';
export {InjectionToken, OpaqueToken} from './di/injection_token';

View File

@ -26,10 +26,42 @@
*
* Using an `OpaqueToken` is preferable to using an `Object` as tokens because it provides better
* error messages.
* @stable
* @deprecated since v4.0.0 because it does not support type information, use `InjectionToken<?>`
* instead.
*/
export class OpaqueToken {
constructor(private _desc: string) {}
constructor(protected _desc: string) {}
toString(): string { return `Token ${this._desc}`; }
}
/**
* 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
*
* {@example core/di/ts/injector_spec.ts region='Injector'}
*
* @stable
*/
export class InjectionToken<T> extends OpaqueToken {
// This unused property is needed here so that TS can differentiate InjectionToken from
// OpaqueToken since otherwise they would have the same shape and be treated as equivalent.
private _differentiate_from_OpaqueToken_structurally: any;
constructor(desc: string) { super(desc); }
toString(): string { return `InjectionToken ${this._desc}`; }
}

View File

@ -8,6 +8,9 @@
import {unimplemented} from '../facade/errors';
import {stringify} from '../facade/lang';
import {Type} from '../type';
import {InjectionToken} from './injection_token';
const _THROW_IF_NOT_FOUND = new Object();
export const THROW_IF_NOT_FOUND = _THROW_IF_NOT_FOUND;
@ -52,5 +55,10 @@ export abstract class Injector {
* Injector.THROW_IF_NOT_FOUND is given
* - Returns the `notFoundValue` otherwise
*/
get<T>(token: Type<T>|InjectionToken<T>, notFoundValue?: T): T;
/**
* @deprecated from v4.0.0 use Type<T> or InjectToken<T>
*/
get(token: any, notFoundValue?: any): any;
get(token: any, notFoundValue?: any): any { return unimplemented(); }
}

View File

@ -52,7 +52,7 @@ export interface TypeProvider extends Type<any> {}
*/
export interface ValueProvider {
/**
* An injection token. (Typically an instance of `Type` or `OpaqueToken`, but can be `any`).
* An injection token. (Typically an instance of `Type` or `InjectionToken`, but can be `any`).
*/
provide: any;
@ -96,7 +96,7 @@ export interface ValueProvider {
*/
export interface ClassProvider {
/**
* An injection token. (Typically an instance of `Type` or `OpaqueToken`, but can be `any`).
* An injection token. (Typically an instance of `Type` or `InjectionToken`, but can be `any`).
*/
provide: any;
@ -134,7 +134,7 @@ export interface ClassProvider {
*/
export interface ExistingProvider {
/**
* An injection token. (Typically an instance of `Type` or `OpaqueToken`, but can be `any`).
* An injection token. (Typically an instance of `Type` or `InjectionToken`, but can be `any`).
*/
provide: any;
@ -178,7 +178,7 @@ export interface ExistingProvider {
*/
export interface FactoryProvider {
/**
* An injection token. (Typically an instance of `Type` or `OpaqueToken`, but can be `any`).
* An injection token. (Typically an instance of `Type` or `InjectionToken`, but can be `any`).
*/
provide: any;

View File

@ -6,19 +6,19 @@
* found in the LICENSE file at https://angular.io/license
*/
import {OpaqueToken} from '../di/opaque_token';
import {InjectionToken} from '../di/injection_token';
/**
* @experimental i18n support is experimental.
*/
export const LOCALE_ID = new OpaqueToken('LocaleId');
export const LOCALE_ID = new InjectionToken<string>('LocaleId');
/**
* @experimental i18n support is experimental.
*/
export const TRANSLATIONS = new OpaqueToken('Translations');
export const TRANSLATIONS = new InjectionToken<string>('Translations');
/**
* @experimental i18n support is experimental.
*/
export const TRANSLATIONS_FORMAT = new OpaqueToken('TranslationsFormat');
export const TRANSLATIONS_FORMAT = new InjectionToken<string>('TranslationsFormat');

View File

@ -6,7 +6,7 @@
* found in the LICENSE file at https://angular.io/license
*/
import {Injectable, OpaqueToken} from '../di';
import {Injectable, InjectionToken} from '../di';
import {BaseError} from '../facade/errors';
import {stringify} from '../facade/lang';
import {ViewEncapsulation} from '../metadata';
@ -119,7 +119,7 @@ export type CompilerOptions = {
*
* @experimental
*/
export const COMPILER_OPTIONS = new OpaqueToken('compilerOptions');
export const COMPILER_OPTIONS = new InjectionToken<CompilerOptions[]>('compilerOptions');
/**
* A factory for creating a Compiler

View File

@ -6,7 +6,7 @@
* found in the LICENSE file at https://angular.io/license
*/
import {OpaqueToken} from '../di/opaque_token';
import {InjectionToken} from '../di/injection_token';
import {Type} from '../type';
import {makeParamDecorator, makePropDecorator} from '../util/decorators';
@ -44,7 +44,7 @@ import {makeParamDecorator, makePropDecorator} from '../util/decorators';
*
* @experimental
*/
export const ANALYZE_FOR_ENTRY_COMPONENTS = new OpaqueToken('AnalyzeForEntryComponents');
export const ANALYZE_FOR_ENTRY_COMPONENTS = new InjectionToken<any>('AnalyzeForEntryComponents');
/**
* Type of the Attribute decorator / constructor function.

View File

@ -7,7 +7,7 @@
*/
import {CommonModule} from '@angular/common';
import {ComponentFactory, Host, Inject, Injectable, Injector, NO_ERRORS_SCHEMA, NgModule, OnDestroy, OpaqueToken, ReflectiveInjector, SkipSelf} from '@angular/core';
import {ComponentFactory, Host, Inject, Injectable, InjectionToken, Injector, NO_ERRORS_SCHEMA, NgModule, OnDestroy, ReflectiveInjector, SkipSelf} from '@angular/core';
import {ChangeDetectionStrategy, ChangeDetectorRef, PipeTransform} from '@angular/core/src/change_detection/change_detection';
import {ComponentFactoryResolver} from '@angular/core/src/linker/component_factory_resolver';
import {ElementRef} from '@angular/core/src/linker/element_ref';
@ -25,7 +25,7 @@ import {expect} from '@angular/platform-browser/testing/matchers';
import {EventEmitter} from '../../src/facade/async';
import {isBlank, isPresent, stringify} from '../../src/facade/lang';
const ANCHOR_ELEMENT = new OpaqueToken('AnchorElement');
const ANCHOR_ELEMENT = new InjectionToken('AnchorElement');
export function main() {
describe('jit', () => { declareTests({useJit: true}); });

View File

@ -6,7 +6,7 @@
* found in the LICENSE file at https://angular.io/license
*/
import {ANALYZE_FOR_ENTRY_COMPONENTS, CUSTOM_ELEMENTS_SCHEMA, Compiler, Component, ComponentFactoryResolver, Directive, HostBinding, Inject, Injectable, Injector, Input, NgModule, NgModuleRef, Optional, Pipe, Provider, Self, Type, forwardRef, getModuleFactory} from '@angular/core';
import {ANALYZE_FOR_ENTRY_COMPONENTS, CUSTOM_ELEMENTS_SCHEMA, Compiler, Component, ComponentFactoryResolver, Directive, HostBinding, Inject, Injectable, InjectionToken, Injector, Input, NgModule, NgModuleRef, Optional, Pipe, Provider, Self, Type, forwardRef, getModuleFactory} from '@angular/core';
import {Console} from '@angular/core/src/console';
import {ComponentFixture, TestBed, inject} from '@angular/core/testing';
import {expect} from '@angular/platform-browser/testing/matchers';
@ -30,6 +30,7 @@ class Dashboard {
class TurboEngine extends Engine {}
const CARS = new InjectionToken<Car[]>('Cars');
@Injectable()
class Car {
engine: Engine;
@ -692,11 +693,11 @@ function declareTests({useJit}: {useJit: boolean}) {
it('should support multiProviders', () => {
const injector = createInjector([
Engine, {provide: Car, useClass: SportsCar, multi: true},
{provide: Car, useClass: CarWithOptionalEngine, multi: true}
Engine, {provide: CARS, useClass: SportsCar, multi: true},
{provide: CARS, useClass: CarWithOptionalEngine, multi: true}
]);
const cars = injector.get(Car);
const cars = injector.get(CARS);
expect(cars.length).toEqual(2);
expect(cars[0]).toBeAnInstanceOf(SportsCar);
expect(cars[1]).toBeAnInstanceOf(CarWithOptionalEngine);
@ -704,9 +705,9 @@ function declareTests({useJit}: {useJit: boolean}) {
it('should support multiProviders that are created using useExisting', () => {
const injector = createInjector(
[Engine, SportsCar, {provide: Car, useExisting: SportsCar, multi: true}]);
[Engine, SportsCar, {provide: CARS, useExisting: SportsCar, multi: true}]);
const cars = injector.get(Car);
const cars = injector.get(CARS);
expect(cars.length).toEqual(1);
expect(cars[0]).toBe(injector.get(SportsCar));
});

View File

@ -6,7 +6,7 @@
* found in the LICENSE file at https://angular.io/license
*/
import {ANALYZE_FOR_ENTRY_COMPONENTS, Component, Injector, OpaqueToken, Pipe, PipeTransform, Provider} from '@angular/core';
import {ANALYZE_FOR_ENTRY_COMPONENTS, Component, InjectionToken, Injector, Pipe, PipeTransform, Provider} from '@angular/core';
import {TestBed} from '@angular/core/testing';
import {expect} from '@angular/platform-browser/testing/matchers';
@ -104,8 +104,8 @@ function declareTests({useJit}: {useJit: boolean}) {
return TestBed.createComponent(MyComp1).componentInstance.injector;
}
it('should support providers with an OpaqueToken that contains a `.` in the name', () => {
const token = new OpaqueToken('a.b');
it('should support providers with an InjectionToken that contains a `.` in the name', () => {
const token = new InjectionToken('a.b');
const tokenValue = 1;
const injector = createInjector([{provide: token, useValue: tokenValue}]);
expect(injector.get(token)).toEqual(tokenValue);
@ -127,9 +127,9 @@ function declareTests({useJit}: {useJit: boolean}) {
expect(injector.get(token)).toEqual(tokenValue);
});
it('should support providers with an OpaqueToken that has a StringMap as value', () => {
const token1 = new OpaqueToken('someToken');
const token2 = new OpaqueToken('someToken');
it('should support providers with an InjectionToken that has a StringMap as value', () => {
const token1 = new InjectionToken('someToken');
const token2 = new InjectionToken('someToken');
const tokenValue1 = {'a': 1};
const tokenValue2 = {'a': 1};
const injector = createInjector(

View File

@ -6,7 +6,7 @@
* found in the LICENSE file at https://angular.io/license
*/
import {CompilerOptions, Component, Directive, Injector, ModuleWithComponentFactories, NgModule, NgModuleRef, NgZone, OpaqueToken, Pipe, PlatformRef, Provider, ReflectiveInjector, SchemaMetadata, Type} from '@angular/core';
import {CompilerOptions, Component, Directive, InjectionToken, Injector, ModuleWithComponentFactories, NgModule, NgModuleRef, NgZone, Pipe, PlatformRef, Provider, ReflectiveInjector, SchemaMetadata, Type} from '@angular/core';
import {AsyncTestCompleter} from './async_test_completer';
import {ComponentFixture} from './component_fixture';
@ -30,12 +30,13 @@ let _nextRootElementId = 0;
/**
* @experimental
*/
export const ComponentFixtureAutoDetect = new OpaqueToken('ComponentFixtureAutoDetect');
export const ComponentFixtureAutoDetect =
new InjectionToken<boolean[]>('ComponentFixtureAutoDetect');
/**
* @experimental
*/
export const ComponentFixtureNoNgZone = new OpaqueToken('ComponentFixtureNoNgZone');
export const ComponentFixtureNoNgZone = new InjectionToken<boolean[]>('ComponentFixtureNoNgZone');
/**
* @experimental