Concrete injectors implement this interface. Injectors are configured with providers that associate dependencies of various types with injection tokens.
API
abstract class Injector {
abstract get<T>(token: ProviderToken<T>, notFoundValue: undefined, options: InjectOptions & { optional?: false | undefined; }): T;
abstract get<T>(token: ProviderToken<T>, notFoundValue: null | undefined, options: InjectOptions): T | null;
abstract get<T>(token: ProviderToken<T>, notFoundValue?: T | undefined, options?: InjectOptions | undefined): T;
abstract get<T>(token: string | ProviderToken<T>, notFoundValue?: any): any;
static THROW_IF_NOT_FOUND: {};
static NULL: Injector;
static create(providers: StaticProvider[], parent?: Injector | undefined): Injector;
static create(options: { providers: (any[] | TypeProvider | ValueProvider | ClassProvider | ConstructorProvider | ExistingProvider | FactoryProvider | StaticClassProvider)[]; parent?: Injector | undefined; name?: string | undefined; }): DestroyableInjector;
}
get
4 overloadsRetrieves an instance from the injector based on the provided token.
undefined
T
Retrieves an instance from the injector based on the provided token.
null | undefined
T | null
Retrieves an instance from the injector based on the provided token.
T | undefined
T
THROW_IF_NOT_FOUND
{}NULL
Injectorcreate
2 overloadsCreates a new injector instance that provides one or more dependencies, according to a given type or types of StaticProvider.
{ providers: (any[] | TypeProvider | ValueProvider | ClassProvider | ConstructorProvider | ExistingProvider | FactoryProvider | StaticClassProvider)[]; parent?: Injector | undefined; name?: string | undefined; }An object with the following properties:
-
providers: An array of providers of the StaticProvider type. -
parent: (optional) A parent injector. -
name: (optional) A developer-defined identifying name for the new injector.
DestroyableInjector
Usage Notes
The following example creates a service injector instance.
class Square {
name = 'square';
}
const injector = Injector.create({providers: [{provide: Square, deps: []}]});
const shape: Square = injector.get(Square);
expect(shape.name).toEqual('square');
expect(shape instanceof Square).toBe(true); Usage example
const injector: Injector = Injector.create({
providers: [{provide: 'validToken', useValue: 'Value'}],
});
expect(injector.get('validToken')).toEqual('Value');
expect(() => injector.get('invalidToken')).toThrowError();
expect(injector.get('invalidToken', 'notFound')).toEqual('notFound');
Injector returns itself when given Injector as a token:
const injector = Injector.create({providers: []});
expect(injector.get(Injector)).toBe(injector);