Injector

Concrete injectors implement this interface.

See more...

abstract class Injector { static THROW_IF_NOT_FOUND: _THROW_IF_NOT_FOUND static NULL: Injector static ngInjectableDef: defineInjectable({...}) static create(options: StaticProvider[] | {...}, parent?: Injector): Injector abstract get<T>(token: Type<T> | InjectionToken<T>, notFoundValue?: T, flags?: InjectFlags): T }

说明

For more details, see the "Dependency Injection Guide".

静态属性

属性说明
static THROW_IF_NOT_FOUND: _THROW_IF_NOT_FOUND
static NULL: Injector
static ngInjectableDef: defineInjectable({ providedIn: 'any' as any, factory: () => inject(INJECTOR) })

静态方法

Create a new Injector which is configure using StaticProviders.

static create(providers: StaticProvider[], parent?: Injector): Injector

Deprecated from v5 use the new signature Injector.create(options)

参数

providers

Type: StaticProvider[].

parent

Type: Injector.

可选. 默认值是 undefined.

返回值

Injector

static create(options: { providers: StaticProvider[]; parent?: Injector; name?: string; }): Injector

参数

options

Type: { providers: StaticProvider[]; parent?: Injector; name?: string; }.

返回值

Injector

Example

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);

方法

Retrieves an instance from the injector based on the provided token.

abstract get<T>(token: Type<T> | InjectionToken<T>, notFoundValue?: T, flags?: InjectFlags): T

参数

token

Type: Type | InjectionToken.

notFoundValue

Type: T.

可选. 默认值是 undefined.

flags

Type: InjectFlags.

可选. 默认值是 undefined.

返回值

T: The instance from the injector if defined, otherwise the notFoundValue.

异常

错误 When the notFoundValue is undefined or Injector.THROW_IF_NOT_FOUND.

abstract get(token: any, notFoundValue?: any): any

Deprecated from v4.0.0 use Typeor InjectionToken

参数

token

Type: any.

notFoundValue

Type: any.

可选. 默认值是 undefined.

返回值

any

使用说明

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);