2016-06-23 09:47:54 -07:00
|
|
|
/**
|
|
|
|
|
* @license
|
|
|
|
|
* Copyright Google Inc. All Rights Reserved.
|
|
|
|
|
*
|
|
|
|
|
* Use of this source code is governed by an MIT-style license that can be
|
|
|
|
|
* found in the LICENSE file at https://angular.io/license
|
|
|
|
|
*/
|
|
|
|
|
|
2017-01-03 16:54:46 -08:00
|
|
|
import {Type} from '../type';
|
2017-03-02 09:37:01 -08:00
|
|
|
import {stringify} from '../util';
|
2018-02-16 08:45:21 -08:00
|
|
|
|
|
|
|
|
import {InjectableDef, defineInjectable} from './defs';
|
2017-07-27 13:49:33 -07:00
|
|
|
import {resolveForwardRef} from './forward_ref';
|
2017-01-03 16:54:46 -08:00
|
|
|
import {InjectionToken} from './injection_token';
|
2017-07-27 13:49:33 -07:00
|
|
|
import {Inject, Optional, Self, SkipSelf} from './metadata';
|
|
|
|
|
import {ConstructorProvider, ExistingProvider, FactoryProvider, StaticClassProvider, StaticProvider, ValueProvider} from './provider';
|
2015-09-02 10:21:28 -07:00
|
|
|
|
2017-12-06 10:13:50 +01:00
|
|
|
export const SOURCE = '__source';
|
2016-07-30 19:18:14 -07:00
|
|
|
const _THROW_IF_NOT_FOUND = new Object();
|
|
|
|
|
export const THROW_IF_NOT_FOUND = _THROW_IF_NOT_FOUND;
|
2015-07-06 10:38:12 -07:00
|
|
|
|
2018-02-16 08:45:21 -08:00
|
|
|
/**
|
|
|
|
|
* An InjectionToken that gets the current `Injector` for `createInjector()`-style injectors.
|
|
|
|
|
*
|
|
|
|
|
* Requesting this token instead of `Injector` allows `StaticInjector` to be tree-shaken from a
|
|
|
|
|
* project.
|
|
|
|
|
*
|
|
|
|
|
* @experimental
|
|
|
|
|
*/
|
|
|
|
|
export const INJECTOR = new InjectionToken<Injector>('INJECTOR');
|
|
|
|
|
|
|
|
|
|
export class NullInjector implements Injector {
|
2016-06-28 09:54:42 -07:00
|
|
|
get(token: any, notFoundValue: any = _THROW_IF_NOT_FOUND): any {
|
|
|
|
|
if (notFoundValue === _THROW_IF_NOT_FOUND) {
|
2017-07-27 13:49:33 -07:00
|
|
|
throw new Error(`NullInjectorError: No provider for ${stringify(token)}!`);
|
2016-06-28 09:54:42 -07:00
|
|
|
}
|
|
|
|
|
return notFoundValue;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2016-05-25 15:00:05 -07:00
|
|
|
/**
|
2016-09-14 09:43:01 -07:00
|
|
|
* @whatItDoes Injector interface
|
|
|
|
|
* @howToUse
|
|
|
|
|
* ```
|
|
|
|
|
* const injector: Injector = ...;
|
|
|
|
|
* injector.get(...);
|
|
|
|
|
* ```
|
|
|
|
|
*
|
|
|
|
|
* @description
|
|
|
|
|
* For more details, see the {@linkDocs guide/dependency-injection "Dependency Injection Guide"}.
|
|
|
|
|
*
|
|
|
|
|
* ### Example
|
|
|
|
|
*
|
|
|
|
|
* {@example core/di/ts/injector_spec.ts region='Injector'}
|
|
|
|
|
*
|
|
|
|
|
* `Injector` returns itself when given `Injector` as a token:
|
|
|
|
|
* {@example core/di/ts/injector_spec.ts region='injectInjector'}
|
|
|
|
|
*
|
2016-05-25 15:00:05 -07:00
|
|
|
* @stable
|
|
|
|
|
*/
|
2016-01-06 14:13:44 -08:00
|
|
|
export abstract class Injector {
|
2016-04-14 12:35:24 -07:00
|
|
|
static THROW_IF_NOT_FOUND = _THROW_IF_NOT_FOUND;
|
2018-02-16 08:45:21 -08:00
|
|
|
static NULL: Injector = new NullInjector();
|
2015-10-10 22:11:13 -07:00
|
|
|
|
2015-06-29 11:15:49 -07:00
|
|
|
/**
|
2015-09-21 14:19:03 -07:00
|
|
|
* Retrieves an instance from the injector based on the provided token.
|
2016-04-14 12:35:24 -07:00
|
|
|
* If not found:
|
2017-04-25 02:15:33 +02:00
|
|
|
* - Throws an error if no `notFoundValue` that is not equal to
|
2016-04-14 12:35:24 -07:00
|
|
|
* Injector.THROW_IF_NOT_FOUND is given
|
|
|
|
|
* - Returns the `notFoundValue` otherwise
|
2015-06-29 11:15:49 -07:00
|
|
|
*/
|
feat: change @Injectable() to support tree-shakeable tokens (#22005)
This commit bundles 3 important changes, with the goal of enabling tree-shaking
of services which are never injected. Ordinarily, this tree-shaking is prevented
by the existence of a hard dependency on the service by the module in which it
is declared.
Firstly, @Injectable() is modified to accept a 'scope' parameter, which points
to an @NgModule(). This reverses the dependency edge, permitting the module to
not depend on the service which it "provides".
Secondly, the runtime is modified to understand the new relationship created
above. When a module receives a request to inject a token, and cannot find that
token in its list of providers, it will then look at the token for a special
ngInjectableDef field which indicates which module the token is scoped to. If
that module happens to be in the injector, it will behave as if the token
itself was in the injector to begin with.
Thirdly, the compiler is modified to read the @Injectable() metadata and to
generate the special ngInjectableDef field as part of TS compilation, using the
PartialModules system.
Additionally, this commit adds several unit and integration tests of various
flavors to test this change.
PR Close #22005
2018-02-02 10:33:48 -08:00
|
|
|
abstract get<T>(token: Type<T>|InjectionToken<T>, notFoundValue?: T, flags?: InjectFlags): T;
|
2017-01-03 16:54:46 -08:00
|
|
|
/**
|
2017-03-07 05:08:02 +02:00
|
|
|
* @deprecated from v4.0.0 use Type<T> or InjectionToken<T>
|
2017-01-30 16:25:15 -08:00
|
|
|
* @suppress {duplicate}
|
2017-01-03 16:54:46 -08:00
|
|
|
*/
|
2017-01-25 22:32:32 -08:00
|
|
|
abstract get(token: any, notFoundValue?: any): any;
|
2017-07-27 13:49:33 -07:00
|
|
|
|
2017-12-06 10:13:50 +01:00
|
|
|
/**
|
|
|
|
|
* @deprecated from v5 use the new signature Injector.create(options)
|
|
|
|
|
*/
|
|
|
|
|
static create(providers: StaticProvider[], parent?: Injector): Injector;
|
|
|
|
|
|
|
|
|
|
static create(options: {providers: StaticProvider[], parent?: Injector, name?: string}): Injector;
|
|
|
|
|
|
2017-07-27 13:49:33 -07:00
|
|
|
/**
|
|
|
|
|
* Create a new Injector which is configure using `StaticProvider`s.
|
|
|
|
|
*
|
|
|
|
|
* ### Example
|
|
|
|
|
*
|
|
|
|
|
* {@example core/di/ts/provider_spec.ts region='ConstructorProvider'}
|
|
|
|
|
*/
|
2017-12-06 10:13:50 +01:00
|
|
|
static create(
|
|
|
|
|
options: StaticProvider[]|{providers: StaticProvider[], parent?: Injector, name?: string},
|
|
|
|
|
parent?: Injector): Injector {
|
|
|
|
|
if (Array.isArray(options)) {
|
|
|
|
|
return new StaticInjector(options, parent);
|
|
|
|
|
} else {
|
|
|
|
|
return new StaticInjector(options.providers, options.parent, options.name || null);
|
|
|
|
|
}
|
2017-07-27 13:49:33 -07:00
|
|
|
}
|
2018-02-16 08:45:21 -08:00
|
|
|
|
|
|
|
|
static ngInjectableDef = defineInjectable({
|
|
|
|
|
providedIn: 'any' as any,
|
|
|
|
|
factory: () => inject(INJECTOR),
|
|
|
|
|
});
|
2017-07-27 13:49:33 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
const IDENT = function<T>(value: T): T {
|
|
|
|
|
return value;
|
|
|
|
|
};
|
|
|
|
|
const EMPTY = <any[]>[];
|
|
|
|
|
const CIRCULAR = IDENT;
|
|
|
|
|
const MULTI_PROVIDER_FN = function(): any[] {
|
|
|
|
|
return Array.prototype.slice.call(arguments);
|
|
|
|
|
};
|
|
|
|
|
const GET_PROPERTY_NAME = {} as any;
|
2018-02-16 08:45:21 -08:00
|
|
|
export const USE_VALUE =
|
2017-07-27 13:49:33 -07:00
|
|
|
getClosureSafeProperty<ValueProvider>({provide: String, useValue: GET_PROPERTY_NAME});
|
|
|
|
|
const NG_TOKEN_PATH = 'ngTokenPath';
|
|
|
|
|
const NG_TEMP_TOKEN_PATH = 'ngTempTokenPath';
|
|
|
|
|
const enum OptionFlags {
|
|
|
|
|
Optional = 1 << 0,
|
|
|
|
|
CheckSelf = 1 << 1,
|
|
|
|
|
CheckParent = 1 << 2,
|
|
|
|
|
Default = CheckSelf | CheckParent
|
|
|
|
|
}
|
|
|
|
|
const NULL_INJECTOR = Injector.NULL;
|
|
|
|
|
const NEW_LINE = /\n/gm;
|
|
|
|
|
const NO_NEW_LINE = 'ɵ';
|
|
|
|
|
|
|
|
|
|
export class StaticInjector implements Injector {
|
|
|
|
|
readonly parent: Injector;
|
2017-12-06 10:13:50 +01:00
|
|
|
readonly source: string|null;
|
2017-07-27 13:49:33 -07:00
|
|
|
|
|
|
|
|
private _records: Map<any, Record>;
|
|
|
|
|
|
2017-12-06 10:13:50 +01:00
|
|
|
constructor(
|
|
|
|
|
providers: StaticProvider[], parent: Injector = NULL_INJECTOR, source: string|null = null) {
|
2017-07-27 13:49:33 -07:00
|
|
|
this.parent = parent;
|
2017-12-06 10:13:50 +01:00
|
|
|
this.source = source;
|
2017-07-27 13:49:33 -07:00
|
|
|
const records = this._records = new Map<any, Record>();
|
|
|
|
|
records.set(
|
|
|
|
|
Injector, <Record>{token: Injector, fn: IDENT, deps: EMPTY, value: this, useNew: false});
|
2018-02-16 08:45:21 -08:00
|
|
|
records.set(
|
|
|
|
|
INJECTOR, <Record>{token: Injector, fn: IDENT, deps: EMPTY, value: this, useNew: false});
|
2017-07-27 13:49:33 -07:00
|
|
|
recursivelyProcessProviders(records, providers);
|
|
|
|
|
}
|
|
|
|
|
|
feat: change @Injectable() to support tree-shakeable tokens (#22005)
This commit bundles 3 important changes, with the goal of enabling tree-shaking
of services which are never injected. Ordinarily, this tree-shaking is prevented
by the existence of a hard dependency on the service by the module in which it
is declared.
Firstly, @Injectable() is modified to accept a 'scope' parameter, which points
to an @NgModule(). This reverses the dependency edge, permitting the module to
not depend on the service which it "provides".
Secondly, the runtime is modified to understand the new relationship created
above. When a module receives a request to inject a token, and cannot find that
token in its list of providers, it will then look at the token for a special
ngInjectableDef field which indicates which module the token is scoped to. If
that module happens to be in the injector, it will behave as if the token
itself was in the injector to begin with.
Thirdly, the compiler is modified to read the @Injectable() metadata and to
generate the special ngInjectableDef field as part of TS compilation, using the
PartialModules system.
Additionally, this commit adds several unit and integration tests of various
flavors to test this change.
PR Close #22005
2018-02-02 10:33:48 -08:00
|
|
|
get<T>(token: Type<T>|InjectionToken<T>, notFoundValue?: T, flags?: InjectFlags): T;
|
2017-07-27 13:49:33 -07:00
|
|
|
get(token: any, notFoundValue?: any): any;
|
feat: change @Injectable() to support tree-shakeable tokens (#22005)
This commit bundles 3 important changes, with the goal of enabling tree-shaking
of services which are never injected. Ordinarily, this tree-shaking is prevented
by the existence of a hard dependency on the service by the module in which it
is declared.
Firstly, @Injectable() is modified to accept a 'scope' parameter, which points
to an @NgModule(). This reverses the dependency edge, permitting the module to
not depend on the service which it "provides".
Secondly, the runtime is modified to understand the new relationship created
above. When a module receives a request to inject a token, and cannot find that
token in its list of providers, it will then look at the token for a special
ngInjectableDef field which indicates which module the token is scoped to. If
that module happens to be in the injector, it will behave as if the token
itself was in the injector to begin with.
Thirdly, the compiler is modified to read the @Injectable() metadata and to
generate the special ngInjectableDef field as part of TS compilation, using the
PartialModules system.
Additionally, this commit adds several unit and integration tests of various
flavors to test this change.
PR Close #22005
2018-02-02 10:33:48 -08:00
|
|
|
get(token: any, notFoundValue?: any, flags: InjectFlags = InjectFlags.Default): any {
|
2017-07-27 13:49:33 -07:00
|
|
|
const record = this._records.get(token);
|
|
|
|
|
try {
|
feat: change @Injectable() to support tree-shakeable tokens (#22005)
This commit bundles 3 important changes, with the goal of enabling tree-shaking
of services which are never injected. Ordinarily, this tree-shaking is prevented
by the existence of a hard dependency on the service by the module in which it
is declared.
Firstly, @Injectable() is modified to accept a 'scope' parameter, which points
to an @NgModule(). This reverses the dependency edge, permitting the module to
not depend on the service which it "provides".
Secondly, the runtime is modified to understand the new relationship created
above. When a module receives a request to inject a token, and cannot find that
token in its list of providers, it will then look at the token for a special
ngInjectableDef field which indicates which module the token is scoped to. If
that module happens to be in the injector, it will behave as if the token
itself was in the injector to begin with.
Thirdly, the compiler is modified to read the @Injectable() metadata and to
generate the special ngInjectableDef field as part of TS compilation, using the
PartialModules system.
Additionally, this commit adds several unit and integration tests of various
flavors to test this change.
PR Close #22005
2018-02-02 10:33:48 -08:00
|
|
|
return tryResolveToken(token, record, this._records, this.parent, notFoundValue, flags);
|
2017-07-27 13:49:33 -07:00
|
|
|
} catch (e) {
|
|
|
|
|
const tokenPath: any[] = e[NG_TEMP_TOKEN_PATH];
|
2017-12-06 10:13:50 +01:00
|
|
|
if (token[SOURCE]) {
|
|
|
|
|
tokenPath.unshift(token[SOURCE]);
|
|
|
|
|
}
|
|
|
|
|
e.message = formatError('\n' + e.message, tokenPath, this.source);
|
2017-07-27 13:49:33 -07:00
|
|
|
e[NG_TOKEN_PATH] = tokenPath;
|
|
|
|
|
e[NG_TEMP_TOKEN_PATH] = null;
|
|
|
|
|
throw e;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
toString() {
|
|
|
|
|
const tokens = <string[]>[], records = this._records;
|
|
|
|
|
records.forEach((v, token) => tokens.push(stringify(token)));
|
|
|
|
|
return `StaticInjector[${tokens.join(', ')}]`;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
type SupportedProvider =
|
|
|
|
|
ValueProvider | ExistingProvider | StaticClassProvider | ConstructorProvider | FactoryProvider;
|
|
|
|
|
|
|
|
|
|
interface Record {
|
|
|
|
|
fn: Function;
|
|
|
|
|
useNew: boolean;
|
|
|
|
|
deps: DependencyRecord[];
|
|
|
|
|
value: any;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
interface DependencyRecord {
|
|
|
|
|
token: any;
|
|
|
|
|
options: number;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
type TokenPath = Array<any>;
|
|
|
|
|
|
|
|
|
|
function resolveProvider(provider: SupportedProvider): Record {
|
|
|
|
|
const deps = computeDeps(provider);
|
|
|
|
|
let fn: Function = IDENT;
|
|
|
|
|
let value: any = EMPTY;
|
|
|
|
|
let useNew: boolean = false;
|
|
|
|
|
let provide = resolveForwardRef(provider.provide);
|
|
|
|
|
if (USE_VALUE in provider) {
|
|
|
|
|
// We need to use USE_VALUE in provider since provider.useValue could be defined as undefined.
|
|
|
|
|
value = (provider as ValueProvider).useValue;
|
|
|
|
|
} else if ((provider as FactoryProvider).useFactory) {
|
|
|
|
|
fn = (provider as FactoryProvider).useFactory;
|
|
|
|
|
} else if ((provider as ExistingProvider).useExisting) {
|
|
|
|
|
// Just use IDENT
|
|
|
|
|
} else if ((provider as StaticClassProvider).useClass) {
|
|
|
|
|
useNew = true;
|
|
|
|
|
fn = resolveForwardRef((provider as StaticClassProvider).useClass);
|
|
|
|
|
} else if (typeof provide == 'function') {
|
|
|
|
|
useNew = true;
|
|
|
|
|
fn = provide;
|
|
|
|
|
} else {
|
|
|
|
|
throw staticError(
|
|
|
|
|
'StaticProvider does not have [useValue|useFactory|useExisting|useClass] or [provide] is not newable',
|
|
|
|
|
provider);
|
|
|
|
|
}
|
|
|
|
|
return {deps, fn, useNew, value};
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function multiProviderMixError(token: any) {
|
|
|
|
|
return staticError('Cannot mix multi providers and regular providers', token);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function recursivelyProcessProviders(records: Map<any, Record>, provider: StaticProvider) {
|
|
|
|
|
if (provider) {
|
|
|
|
|
provider = resolveForwardRef(provider);
|
|
|
|
|
if (provider instanceof Array) {
|
|
|
|
|
// if we have an array recurse into the array
|
|
|
|
|
for (let i = 0; i < provider.length; i++) {
|
|
|
|
|
recursivelyProcessProviders(records, provider[i]);
|
|
|
|
|
}
|
|
|
|
|
} else if (typeof provider === 'function') {
|
|
|
|
|
// Functions were supported in ReflectiveInjector, but are not here. For safety give useful
|
|
|
|
|
// error messages
|
|
|
|
|
throw staticError('Function/Class not supported', provider);
|
|
|
|
|
} else if (provider && typeof provider === 'object' && provider.provide) {
|
|
|
|
|
// At this point we have what looks like a provider: {provide: ?, ....}
|
|
|
|
|
let token = resolveForwardRef(provider.provide);
|
|
|
|
|
const resolvedProvider = resolveProvider(provider);
|
|
|
|
|
if (provider.multi === true) {
|
|
|
|
|
// This is a multi provider.
|
|
|
|
|
let multiProvider: Record|undefined = records.get(token);
|
|
|
|
|
if (multiProvider) {
|
|
|
|
|
if (multiProvider.fn !== MULTI_PROVIDER_FN) {
|
|
|
|
|
throw multiProviderMixError(token);
|
|
|
|
|
}
|
|
|
|
|
} else {
|
|
|
|
|
// Create a placeholder factory which will look up the constituents of the multi provider.
|
|
|
|
|
records.set(token, multiProvider = <Record>{
|
|
|
|
|
token: provider.provide,
|
|
|
|
|
deps: [],
|
|
|
|
|
useNew: false,
|
|
|
|
|
fn: MULTI_PROVIDER_FN,
|
|
|
|
|
value: EMPTY
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
// Treat the provider as the token.
|
|
|
|
|
token = provider;
|
|
|
|
|
multiProvider.deps.push({token, options: OptionFlags.Default});
|
|
|
|
|
}
|
|
|
|
|
const record = records.get(token);
|
|
|
|
|
if (record && record.fn == MULTI_PROVIDER_FN) {
|
|
|
|
|
throw multiProviderMixError(token);
|
|
|
|
|
}
|
|
|
|
|
records.set(token, resolvedProvider);
|
|
|
|
|
} else {
|
|
|
|
|
throw staticError('Unexpected provider', provider);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function tryResolveToken(
|
|
|
|
|
token: any, record: Record | undefined, records: Map<any, Record>, parent: Injector,
|
feat: change @Injectable() to support tree-shakeable tokens (#22005)
This commit bundles 3 important changes, with the goal of enabling tree-shaking
of services which are never injected. Ordinarily, this tree-shaking is prevented
by the existence of a hard dependency on the service by the module in which it
is declared.
Firstly, @Injectable() is modified to accept a 'scope' parameter, which points
to an @NgModule(). This reverses the dependency edge, permitting the module to
not depend on the service which it "provides".
Secondly, the runtime is modified to understand the new relationship created
above. When a module receives a request to inject a token, and cannot find that
token in its list of providers, it will then look at the token for a special
ngInjectableDef field which indicates which module the token is scoped to. If
that module happens to be in the injector, it will behave as if the token
itself was in the injector to begin with.
Thirdly, the compiler is modified to read the @Injectable() metadata and to
generate the special ngInjectableDef field as part of TS compilation, using the
PartialModules system.
Additionally, this commit adds several unit and integration tests of various
flavors to test this change.
PR Close #22005
2018-02-02 10:33:48 -08:00
|
|
|
notFoundValue: any, flags: InjectFlags): any {
|
2017-07-27 13:49:33 -07:00
|
|
|
try {
|
feat: change @Injectable() to support tree-shakeable tokens (#22005)
This commit bundles 3 important changes, with the goal of enabling tree-shaking
of services which are never injected. Ordinarily, this tree-shaking is prevented
by the existence of a hard dependency on the service by the module in which it
is declared.
Firstly, @Injectable() is modified to accept a 'scope' parameter, which points
to an @NgModule(). This reverses the dependency edge, permitting the module to
not depend on the service which it "provides".
Secondly, the runtime is modified to understand the new relationship created
above. When a module receives a request to inject a token, and cannot find that
token in its list of providers, it will then look at the token for a special
ngInjectableDef field which indicates which module the token is scoped to. If
that module happens to be in the injector, it will behave as if the token
itself was in the injector to begin with.
Thirdly, the compiler is modified to read the @Injectable() metadata and to
generate the special ngInjectableDef field as part of TS compilation, using the
PartialModules system.
Additionally, this commit adds several unit and integration tests of various
flavors to test this change.
PR Close #22005
2018-02-02 10:33:48 -08:00
|
|
|
return resolveToken(token, record, records, parent, notFoundValue, flags);
|
2017-07-27 13:49:33 -07:00
|
|
|
} catch (e) {
|
|
|
|
|
// ensure that 'e' is of type Error.
|
|
|
|
|
if (!(e instanceof Error)) {
|
|
|
|
|
e = new Error(e);
|
|
|
|
|
}
|
|
|
|
|
const path: any[] = e[NG_TEMP_TOKEN_PATH] = e[NG_TEMP_TOKEN_PATH] || [];
|
|
|
|
|
path.unshift(token);
|
|
|
|
|
if (record && record.value == CIRCULAR) {
|
|
|
|
|
// Reset the Circular flag.
|
|
|
|
|
record.value = EMPTY;
|
|
|
|
|
}
|
|
|
|
|
throw e;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function resolveToken(
|
|
|
|
|
token: any, record: Record | undefined, records: Map<any, Record>, parent: Injector,
|
feat: change @Injectable() to support tree-shakeable tokens (#22005)
This commit bundles 3 important changes, with the goal of enabling tree-shaking
of services which are never injected. Ordinarily, this tree-shaking is prevented
by the existence of a hard dependency on the service by the module in which it
is declared.
Firstly, @Injectable() is modified to accept a 'scope' parameter, which points
to an @NgModule(). This reverses the dependency edge, permitting the module to
not depend on the service which it "provides".
Secondly, the runtime is modified to understand the new relationship created
above. When a module receives a request to inject a token, and cannot find that
token in its list of providers, it will then look at the token for a special
ngInjectableDef field which indicates which module the token is scoped to. If
that module happens to be in the injector, it will behave as if the token
itself was in the injector to begin with.
Thirdly, the compiler is modified to read the @Injectable() metadata and to
generate the special ngInjectableDef field as part of TS compilation, using the
PartialModules system.
Additionally, this commit adds several unit and integration tests of various
flavors to test this change.
PR Close #22005
2018-02-02 10:33:48 -08:00
|
|
|
notFoundValue: any, flags: InjectFlags): any {
|
2017-07-27 13:49:33 -07:00
|
|
|
let value;
|
feat: change @Injectable() to support tree-shakeable tokens (#22005)
This commit bundles 3 important changes, with the goal of enabling tree-shaking
of services which are never injected. Ordinarily, this tree-shaking is prevented
by the existence of a hard dependency on the service by the module in which it
is declared.
Firstly, @Injectable() is modified to accept a 'scope' parameter, which points
to an @NgModule(). This reverses the dependency edge, permitting the module to
not depend on the service which it "provides".
Secondly, the runtime is modified to understand the new relationship created
above. When a module receives a request to inject a token, and cannot find that
token in its list of providers, it will then look at the token for a special
ngInjectableDef field which indicates which module the token is scoped to. If
that module happens to be in the injector, it will behave as if the token
itself was in the injector to begin with.
Thirdly, the compiler is modified to read the @Injectable() metadata and to
generate the special ngInjectableDef field as part of TS compilation, using the
PartialModules system.
Additionally, this commit adds several unit and integration tests of various
flavors to test this change.
PR Close #22005
2018-02-02 10:33:48 -08:00
|
|
|
if (record && !(flags & InjectFlags.SkipSelf)) {
|
2017-07-27 13:49:33 -07:00
|
|
|
// If we don't have a record, this implies that we don't own the provider hence don't know how
|
|
|
|
|
// to resolve it.
|
|
|
|
|
value = record.value;
|
|
|
|
|
if (value == CIRCULAR) {
|
|
|
|
|
throw Error(NO_NEW_LINE + 'Circular dependency');
|
|
|
|
|
} else if (value === EMPTY) {
|
|
|
|
|
record.value = CIRCULAR;
|
|
|
|
|
let obj = undefined;
|
|
|
|
|
let useNew = record.useNew;
|
|
|
|
|
let fn = record.fn;
|
|
|
|
|
let depRecords = record.deps;
|
|
|
|
|
let deps = EMPTY;
|
|
|
|
|
if (depRecords.length) {
|
|
|
|
|
deps = [];
|
|
|
|
|
for (let i = 0; i < depRecords.length; i++) {
|
|
|
|
|
const depRecord: DependencyRecord = depRecords[i];
|
|
|
|
|
const options = depRecord.options;
|
|
|
|
|
const childRecord =
|
|
|
|
|
options & OptionFlags.CheckSelf ? records.get(depRecord.token) : undefined;
|
|
|
|
|
deps.push(tryResolveToken(
|
|
|
|
|
// Current Token to resolve
|
|
|
|
|
depRecord.token,
|
|
|
|
|
// A record which describes how to resolve the token.
|
|
|
|
|
// If undefined, this means we don't have such a record
|
|
|
|
|
childRecord,
|
|
|
|
|
// Other records we know about.
|
|
|
|
|
records,
|
|
|
|
|
// If we don't know how to resolve dependency and we should not check parent for it,
|
|
|
|
|
// than pass in Null injector.
|
|
|
|
|
!childRecord && !(options & OptionFlags.CheckParent) ? NULL_INJECTOR : parent,
|
feat: change @Injectable() to support tree-shakeable tokens (#22005)
This commit bundles 3 important changes, with the goal of enabling tree-shaking
of services which are never injected. Ordinarily, this tree-shaking is prevented
by the existence of a hard dependency on the service by the module in which it
is declared.
Firstly, @Injectable() is modified to accept a 'scope' parameter, which points
to an @NgModule(). This reverses the dependency edge, permitting the module to
not depend on the service which it "provides".
Secondly, the runtime is modified to understand the new relationship created
above. When a module receives a request to inject a token, and cannot find that
token in its list of providers, it will then look at the token for a special
ngInjectableDef field which indicates which module the token is scoped to. If
that module happens to be in the injector, it will behave as if the token
itself was in the injector to begin with.
Thirdly, the compiler is modified to read the @Injectable() metadata and to
generate the special ngInjectableDef field as part of TS compilation, using the
PartialModules system.
Additionally, this commit adds several unit and integration tests of various
flavors to test this change.
PR Close #22005
2018-02-02 10:33:48 -08:00
|
|
|
options & OptionFlags.Optional ? null : Injector.THROW_IF_NOT_FOUND,
|
|
|
|
|
InjectFlags.Default));
|
2017-07-27 13:49:33 -07:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
record.value = value = useNew ? new (fn as any)(...deps) : fn.apply(obj, deps);
|
|
|
|
|
}
|
feat: change @Injectable() to support tree-shakeable tokens (#22005)
This commit bundles 3 important changes, with the goal of enabling tree-shaking
of services which are never injected. Ordinarily, this tree-shaking is prevented
by the existence of a hard dependency on the service by the module in which it
is declared.
Firstly, @Injectable() is modified to accept a 'scope' parameter, which points
to an @NgModule(). This reverses the dependency edge, permitting the module to
not depend on the service which it "provides".
Secondly, the runtime is modified to understand the new relationship created
above. When a module receives a request to inject a token, and cannot find that
token in its list of providers, it will then look at the token for a special
ngInjectableDef field which indicates which module the token is scoped to. If
that module happens to be in the injector, it will behave as if the token
itself was in the injector to begin with.
Thirdly, the compiler is modified to read the @Injectable() metadata and to
generate the special ngInjectableDef field as part of TS compilation, using the
PartialModules system.
Additionally, this commit adds several unit and integration tests of various
flavors to test this change.
PR Close #22005
2018-02-02 10:33:48 -08:00
|
|
|
} else if (!(flags & InjectFlags.Self)) {
|
|
|
|
|
value = parent.get(token, notFoundValue, InjectFlags.Default);
|
2017-07-27 13:49:33 -07:00
|
|
|
}
|
|
|
|
|
return value;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
function computeDeps(provider: StaticProvider): DependencyRecord[] {
|
|
|
|
|
let deps: DependencyRecord[] = EMPTY;
|
|
|
|
|
const providerDeps: any[] =
|
|
|
|
|
(provider as ExistingProvider & StaticClassProvider & ConstructorProvider).deps;
|
|
|
|
|
if (providerDeps && providerDeps.length) {
|
|
|
|
|
deps = [];
|
|
|
|
|
for (let i = 0; i < providerDeps.length; i++) {
|
|
|
|
|
let options = OptionFlags.Default;
|
|
|
|
|
let token = resolveForwardRef(providerDeps[i]);
|
|
|
|
|
if (token instanceof Array) {
|
|
|
|
|
for (let j = 0, annotations = token; j < annotations.length; j++) {
|
|
|
|
|
const annotation = annotations[j];
|
|
|
|
|
if (annotation instanceof Optional || annotation == Optional) {
|
|
|
|
|
options = options | OptionFlags.Optional;
|
|
|
|
|
} else if (annotation instanceof SkipSelf || annotation == SkipSelf) {
|
|
|
|
|
options = options & ~OptionFlags.CheckSelf;
|
|
|
|
|
} else if (annotation instanceof Self || annotation == Self) {
|
|
|
|
|
options = options & ~OptionFlags.CheckParent;
|
|
|
|
|
} else if (annotation instanceof Inject) {
|
|
|
|
|
token = (annotation as Inject).token;
|
|
|
|
|
} else {
|
|
|
|
|
token = resolveForwardRef(annotation);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
deps.push({token, options});
|
|
|
|
|
}
|
|
|
|
|
} else if ((provider as ExistingProvider).useExisting) {
|
|
|
|
|
const token = resolveForwardRef((provider as ExistingProvider).useExisting);
|
|
|
|
|
deps = [{token, options: OptionFlags.Default}];
|
|
|
|
|
} else if (!providerDeps && !(USE_VALUE in provider)) {
|
|
|
|
|
// useValue & useExisting are the only ones which are exempt from deps all others need it.
|
|
|
|
|
throw staticError('\'deps\' required', provider);
|
|
|
|
|
}
|
|
|
|
|
return deps;
|
|
|
|
|
}
|
|
|
|
|
|
2017-12-06 10:13:50 +01:00
|
|
|
function formatError(text: string, obj: any, source: string | null = null): string {
|
2017-07-27 13:49:33 -07:00
|
|
|
text = text && text.charAt(0) === '\n' && text.charAt(1) == NO_NEW_LINE ? text.substr(2) : text;
|
|
|
|
|
let context = stringify(obj);
|
|
|
|
|
if (obj instanceof Array) {
|
|
|
|
|
context = obj.map(stringify).join(' -> ');
|
|
|
|
|
} else if (typeof obj === 'object') {
|
|
|
|
|
let parts = <string[]>[];
|
|
|
|
|
for (let key in obj) {
|
|
|
|
|
if (obj.hasOwnProperty(key)) {
|
|
|
|
|
let value = obj[key];
|
|
|
|
|
parts.push(
|
|
|
|
|
key + ':' + (typeof value === 'string' ? JSON.stringify(value) : stringify(value)));
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
context = `{${parts.join(', ')}}`;
|
|
|
|
|
}
|
2017-12-06 10:13:50 +01:00
|
|
|
return `StaticInjectorError${source ? '(' + source + ')' : ''}[${context}]: ${text.replace(NEW_LINE, '\n ')}`;
|
2017-07-27 13:49:33 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function staticError(text: string, obj: any): Error {
|
|
|
|
|
return new Error(formatError(text, obj));
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function getClosureSafeProperty<T>(objWithPropertyToExtract: T): string {
|
|
|
|
|
for (let key in objWithPropertyToExtract) {
|
|
|
|
|
if (objWithPropertyToExtract[key] === GET_PROPERTY_NAME) {
|
|
|
|
|
return key;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
throw Error('!prop');
|
2015-07-22 12:00:35 -07:00
|
|
|
}
|
feat: change @Injectable() to support tree-shakeable tokens (#22005)
This commit bundles 3 important changes, with the goal of enabling tree-shaking
of services which are never injected. Ordinarily, this tree-shaking is prevented
by the existence of a hard dependency on the service by the module in which it
is declared.
Firstly, @Injectable() is modified to accept a 'scope' parameter, which points
to an @NgModule(). This reverses the dependency edge, permitting the module to
not depend on the service which it "provides".
Secondly, the runtime is modified to understand the new relationship created
above. When a module receives a request to inject a token, and cannot find that
token in its list of providers, it will then look at the token for a special
ngInjectableDef field which indicates which module the token is scoped to. If
that module happens to be in the injector, it will behave as if the token
itself was in the injector to begin with.
Thirdly, the compiler is modified to read the @Injectable() metadata and to
generate the special ngInjectableDef field as part of TS compilation, using the
PartialModules system.
Additionally, this commit adds several unit and integration tests of various
flavors to test this change.
PR Close #22005
2018-02-02 10:33:48 -08:00
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Injection flags for DI.
|
|
|
|
|
*
|
|
|
|
|
* @stable
|
|
|
|
|
*/
|
|
|
|
|
export const enum InjectFlags {
|
|
|
|
|
Default = 0,
|
|
|
|
|
|
|
|
|
|
/** Skip the node that is requesting injection. */
|
|
|
|
|
SkipSelf = 1 << 0,
|
|
|
|
|
/** Don't descend into ancestors of the node requesting injection. */
|
|
|
|
|
Self = 1 << 1,
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
let _currentInjector: Injector|null = null;
|
|
|
|
|
|
|
|
|
|
export function setCurrentInjector(injector: Injector | null): Injector|null {
|
|
|
|
|
const former = _currentInjector;
|
|
|
|
|
_currentInjector = injector;
|
|
|
|
|
return former;
|
|
|
|
|
}
|
|
|
|
|
|
2018-02-23 09:04:55 -08:00
|
|
|
/**
|
|
|
|
|
* Injects a token from the currently active injector.
|
|
|
|
|
*
|
|
|
|
|
* This function must be used in the context of a factory function such as one defined for an
|
|
|
|
|
* `InjectionToken`, and will throw an error if not called from such a context. For example:
|
|
|
|
|
*
|
|
|
|
|
* {@example core/di/ts/injector_spec.ts region='ShakeableInjectionToken'}
|
|
|
|
|
*
|
|
|
|
|
* Within such a factory function `inject` is utilized to request injection of a dependency, instead
|
|
|
|
|
* of providing an additional array of dependencies as was common to do with `useFactory` providers.
|
|
|
|
|
* `inject` is faster and more type-safe.
|
|
|
|
|
*
|
|
|
|
|
* @experimental
|
|
|
|
|
*/
|
feat: change @Injectable() to support tree-shakeable tokens (#22005)
This commit bundles 3 important changes, with the goal of enabling tree-shaking
of services which are never injected. Ordinarily, this tree-shaking is prevented
by the existence of a hard dependency on the service by the module in which it
is declared.
Firstly, @Injectable() is modified to accept a 'scope' parameter, which points
to an @NgModule(). This reverses the dependency edge, permitting the module to
not depend on the service which it "provides".
Secondly, the runtime is modified to understand the new relationship created
above. When a module receives a request to inject a token, and cannot find that
token in its list of providers, it will then look at the token for a special
ngInjectableDef field which indicates which module the token is scoped to. If
that module happens to be in the injector, it will behave as if the token
itself was in the injector to begin with.
Thirdly, the compiler is modified to read the @Injectable() metadata and to
generate the special ngInjectableDef field as part of TS compilation, using the
PartialModules system.
Additionally, this commit adds several unit and integration tests of various
flavors to test this change.
PR Close #22005
2018-02-02 10:33:48 -08:00
|
|
|
export function inject<T>(
|
|
|
|
|
token: Type<T>| InjectionToken<T>, notFoundValue?: undefined, flags?: InjectFlags): T;
|
|
|
|
|
export function inject<T>(
|
|
|
|
|
token: Type<T>| InjectionToken<T>, notFoundValue: T | null, flags?: InjectFlags): T|null;
|
|
|
|
|
export function inject<T>(
|
|
|
|
|
token: Type<T>| InjectionToken<T>, notFoundValue?: T | null, flags = InjectFlags.Default): T|
|
|
|
|
|
null {
|
|
|
|
|
if (_currentInjector === null) {
|
|
|
|
|
throw new Error(`inject() must be called from an injection context`);
|
|
|
|
|
}
|
|
|
|
|
return _currentInjector.get(token, notFoundValue, flags);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export function injectArgs(types: (Type<any>| InjectionToken<any>| any[])[]): any[] {
|
|
|
|
|
const args: any[] = [];
|
|
|
|
|
for (let i = 0; i < types.length; i++) {
|
|
|
|
|
const arg = types[i];
|
|
|
|
|
if (Array.isArray(arg)) {
|
|
|
|
|
if (arg.length === 0) {
|
|
|
|
|
throw new Error('Arguments array must have arguments.');
|
|
|
|
|
}
|
|
|
|
|
let type: Type<any>|undefined = undefined;
|
|
|
|
|
let defaultValue: null|undefined = undefined;
|
|
|
|
|
let flags: InjectFlags = InjectFlags.Default;
|
|
|
|
|
|
|
|
|
|
for (let j = 0; j < arg.length; j++) {
|
|
|
|
|
const meta = arg[j];
|
|
|
|
|
if (meta instanceof Optional || meta.__proto__.ngMetadataName === 'Optional') {
|
|
|
|
|
defaultValue = null;
|
|
|
|
|
} else if (meta instanceof SkipSelf || meta.__proto__.ngMetadataName === 'SkipSelf') {
|
|
|
|
|
flags |= InjectFlags.SkipSelf;
|
|
|
|
|
} else if (meta instanceof Self || meta.__proto__.ngMetadataName === 'Self') {
|
|
|
|
|
flags |= InjectFlags.Self;
|
|
|
|
|
} else if (meta instanceof Inject) {
|
|
|
|
|
type = meta.token;
|
|
|
|
|
} else {
|
|
|
|
|
type = meta;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
args.push(inject(type !, defaultValue, InjectFlags.Default));
|
|
|
|
|
} else {
|
|
|
|
|
args.push(inject(arg));
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
return args;
|
|
|
|
|
}
|