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:

committed by
Miško Hevery

parent
6d1f1a43bb
commit
d169c2434e
@ -17,7 +17,8 @@ const ANGULAR_IMPORT_LOCATIONS = {
|
||||
coreDecorators: '@angular/core/src/metadata',
|
||||
diDecorators: '@angular/core/src/di/metadata',
|
||||
diMetadata: '@angular/core/src/di/metadata',
|
||||
diOpaqueToken: '@angular/core/src/di/opaque_token',
|
||||
diInjectionToken: '@angular/core/src/di/injection_token',
|
||||
diOpaqueToken: '@angular/core/src/di/injection_token',
|
||||
animationMetadata: '@angular/core/src/animation/metadata',
|
||||
provider: '@angular/core/src/di/provider'
|
||||
};
|
||||
@ -34,6 +35,7 @@ export class StaticReflector implements ReflectorReader {
|
||||
private parameterCache = new Map<StaticSymbol, any[]>();
|
||||
private methodCache = new Map<StaticSymbol, {[key: string]: boolean}>();
|
||||
private conversionMap = new Map<StaticSymbol, (context: StaticSymbol, args: any[]) => any>();
|
||||
private injectionToken: StaticSymbol;
|
||||
private opaqueToken: StaticSymbol;
|
||||
|
||||
constructor(
|
||||
@ -229,9 +231,10 @@ export class StaticReflector implements ReflectorReader {
|
||||
}
|
||||
|
||||
private initializeConversionMap(): void {
|
||||
const {coreDecorators, diDecorators, diMetadata, diOpaqueToken, animationMetadata, provider} =
|
||||
ANGULAR_IMPORT_LOCATIONS;
|
||||
this.opaqueToken = this.findDeclaration(diOpaqueToken, 'OpaqueToken');
|
||||
const {coreDecorators, diDecorators, diMetadata, diInjectionToken,
|
||||
diOpaqueToken, animationMetadata, provider} = ANGULAR_IMPORT_LOCATIONS;
|
||||
this.injectionToken = this.findDeclaration(diInjectionToken, 'InjectionToken');
|
||||
this.opaqueToken = this.findDeclaration(diInjectionToken, 'OpaqueToken');
|
||||
|
||||
this._registerDecoratorOrConstructor(this.findDeclaration(diDecorators, 'Host'), Host);
|
||||
this._registerDecoratorOrConstructor(
|
||||
@ -382,7 +385,8 @@ export class StaticReflector implements ReflectorReader {
|
||||
}
|
||||
if (expression instanceof StaticSymbol) {
|
||||
// Stop simplification at builtin symbols
|
||||
if (expression === self.opaqueToken || self.conversionMap.has(expression)) {
|
||||
if (expression === self.injectionToken || expression === self.opaqueToken ||
|
||||
self.conversionMap.has(expression)) {
|
||||
return expression;
|
||||
} else {
|
||||
const staticSymbol = expression;
|
||||
@ -506,9 +510,9 @@ export class StaticReflector implements ReflectorReader {
|
||||
// Determine if the function is a built-in conversion
|
||||
staticSymbol = simplifyInContext(context, expression['expression'], depth + 1);
|
||||
if (staticSymbol instanceof StaticSymbol) {
|
||||
if (staticSymbol === self.opaqueToken) {
|
||||
// if somebody calls new OpaqueToken, don't create an OpaqueToken,
|
||||
// but rather return the symbol to which the OpaqueToken is assigned to.
|
||||
if (staticSymbol === self.injectionToken || staticSymbol === self.opaqueToken) {
|
||||
// if somebody calls new InjectionToken, don't create an InjectionToken,
|
||||
// but rather return the symbol to which the InjectionToken is assigned to.
|
||||
return context;
|
||||
}
|
||||
const argExpressions: any[] = expression['arguments'] || [];
|
||||
@ -674,4 +678,4 @@ function positionalError(message: string, fileName: string, line: number, column
|
||||
(result as any).line = line;
|
||||
(result as any).column = column;
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
@ -6,7 +6,7 @@
|
||||
* found in the LICENSE file at https://angular.io/license
|
||||
*/
|
||||
|
||||
import {COMPILER_OPTIONS, Compiler, CompilerFactory, CompilerOptions, Inject, OpaqueToken, Optional, PLATFORM_INITIALIZER, PlatformRef, Provider, ReflectiveInjector, TRANSLATIONS, TRANSLATIONS_FORMAT, Type, ViewEncapsulation, createPlatformFactory, isDevMode, platformCore} from '@angular/core';
|
||||
import {COMPILER_OPTIONS, Compiler, CompilerFactory, CompilerOptions, Inject, InjectionToken, Optional, PLATFORM_INITIALIZER, PlatformRef, Provider, ReflectiveInjector, TRANSLATIONS, TRANSLATIONS_FORMAT, Type, ViewEncapsulation, createPlatformFactory, isDevMode, platformCore} from '@angular/core';
|
||||
|
||||
import {AnimationParser} from '../animation/animation_parser';
|
||||
import {CompilerConfig} from '../config';
|
||||
@ -40,7 +40,7 @@ const _NO_RESOURCE_LOADER: ResourceLoader = {
|
||||
`No ResourceLoader implementation has been provided. Can't read the url "${url}"`);}
|
||||
};
|
||||
|
||||
const baseHtmlParser = new OpaqueToken('HtmlParser');
|
||||
const baseHtmlParser = new InjectionToken('HtmlParser');
|
||||
|
||||
/**
|
||||
* A set of providers that provide `JitCompiler` and its dependencies to use for
|
||||
|
@ -6,7 +6,7 @@
|
||||
* found in the LICENSE file at https://angular.io/license
|
||||
*/
|
||||
|
||||
import {AnimationAnimateMetadata, AnimationEntryMetadata, AnimationGroupMetadata, AnimationKeyframesSequenceMetadata, AnimationMetadata, AnimationStateDeclarationMetadata, AnimationStateMetadata, AnimationStateTransitionMetadata, AnimationStyleMetadata, AnimationWithStepsMetadata, Attribute, ChangeDetectionStrategy, Component, ComponentFactory, Directive, Host, Inject, Injectable, ModuleWithProviders, OpaqueToken, Optional, Provider, Query, SchemaMetadata, Self, SkipSelf, Type, resolveForwardRef} from '@angular/core';
|
||||
import {AnimationAnimateMetadata, AnimationEntryMetadata, AnimationGroupMetadata, AnimationKeyframesSequenceMetadata, AnimationMetadata, AnimationStateDeclarationMetadata, AnimationStateMetadata, AnimationStateTransitionMetadata, AnimationStyleMetadata, AnimationWithStepsMetadata, Attribute, ChangeDetectionStrategy, Component, ComponentFactory, Directive, Host, Inject, Injectable, InjectionToken, ModuleWithProviders, Optional, Provider, Query, SchemaMetadata, Self, SkipSelf, Type, resolveForwardRef} from '@angular/core';
|
||||
|
||||
import {StaticSymbol, StaticSymbolCache} from './aot/static_symbol';
|
||||
import {ngfactoryFilePath} from './aot/util';
|
||||
@ -27,7 +27,7 @@ import {getUrlScheme} from './url_resolver';
|
||||
import {MODULE_SUFFIX, SyntaxError, ValueTransformer, visitValue} from './util';
|
||||
|
||||
export type ErrorCollector = (error: any, type?: any) => void;
|
||||
export const ERROR_COLLECTOR_TOKEN = new OpaqueToken('ErrorCollector');
|
||||
export const ERROR_COLLECTOR_TOKEN = new InjectionToken('ErrorCollector');
|
||||
|
||||
// Design notes:
|
||||
// - don't lazily create metadata:
|
||||
|
@ -6,7 +6,7 @@
|
||||
* found in the LICENSE file at https://angular.io/license
|
||||
*/
|
||||
|
||||
import {Inject, OpaqueToken, Optional, SchemaMetadata} from '@angular/core';
|
||||
import {Inject, InjectionToken, Optional, SchemaMetadata} from '@angular/core';
|
||||
import {CompileDirectiveMetadata, CompileDirectiveSummary, CompilePipeSummary, CompileTemplateSummary, CompileTokenMetadata, CompileTypeMetadata, identifierName} from '../compile_metadata';
|
||||
import {Parser} from '../expression_parser/parser';
|
||||
import {isPresent} from '../facade/lang';
|
||||
@ -67,7 +67,7 @@ const TEXT_CSS_SELECTOR = CssSelector.parse('*')[0];
|
||||
*
|
||||
* This is currently an internal-only feature and not meant for general use.
|
||||
*/
|
||||
export const TEMPLATE_TRANSFORMS = new OpaqueToken('TemplateTransforms');
|
||||
export const TEMPLATE_TRANSFORMS = new InjectionToken('TemplateTransforms');
|
||||
|
||||
export class TemplateParseError extends ParseError {
|
||||
constructor(message: string, span: ParseSourceSpan, level: ParseErrorLevel) {
|
||||
|
@ -6,12 +6,13 @@
|
||||
* found in the LICENSE file at https://angular.io/license
|
||||
*/
|
||||
|
||||
import {Inject, PACKAGE_ROOT_URL} from '@angular/core';
|
||||
import {Inject, InjectionToken, PACKAGE_ROOT_URL} from '@angular/core';
|
||||
|
||||
import {isBlank, isPresent} from './facade/lang';
|
||||
import {CompilerInjectable} from './injectable';
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Create a {@link UrlResolver} with no package prefix.
|
||||
*/
|
||||
|
Reference in New Issue
Block a user