linkInjector
npm Package | @angular/core |
---|---|
Module | import { Injector } from '@angular/core'; |
Source | core/src/di/injector.ts |
Injector interface
linkOverview
class Injector {
static THROW_IF_NOT_FOUND: _THROW_IF_NOT_FOUND
static NULL: Injector
static create(options: StaticProvider[] | {...}, parent?: Injector): Injector
get<T>(token: Type<T> | InjectionToken<T>, notFoundValue?: T): T
}
linkHow To Use
const injector: Injector = ...;
injector.get(...);
linkDescription
For more details, see the "Dependency Injection Guide".
linkExample
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');
Injector
returns itself when given Injector
as a token:
const injector = ReflectiveInjector.resolveAndCreate([]);
expect(injector.get(Injector)).toBe(injector);
linkSubclasses
linkStatic Members
static THROW_IF_NOT_FOUND: _THROW_IF_NOT_FOUND
static create(options: StaticProvider[] | {
providers: StaticProvider[];
parent?: Injector;
name?: string;
}, parent?: Injector): Injector
Create a new Injector which is configure using StaticProvider
s.
linkExample
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);
Overloads
static create(providers: StaticProvider[], parent?: Injector): Injector
static create(options: {
providers: StaticProvider[];
parent?: Injector;
name?: string;
}): Injector
linkMembers
get<T>(token: Type<T> | InjectionToken<T>, notFoundValue?: T): T
Retrieves an instance from the injector based on the provided token. If not found:
- Throws an error if no
notFoundValue
that is not equal to Injector.THROW_IF_NOT_FOUND is given - Returns the
notFoundValue
otherwise