Injector
具体的注入器会实现此接口。配置有某些提供者的注入器,这些提供者会将各种类型的依赖项与注入令牌相关联。
Concrete injectors implement this interface. Injectors are configured with providers that associate dependencies of various types with injection tokens.
abstract class Injector {
static THROW_IF_NOT_FOUND: THROW_IF_NOT_FOUND
static NULL: Injector
static create(options: StaticProvider[] | { providers: StaticProvider[]; parent?: Injector; name?: string; }, parent?: Injector): Injector
abstract get<T>(token: ProviderToken<T>, notFoundValue?: T, flags?: InjectFlags): T
}
参见
Provided in
'any'
静态属性
属性 | 说明 |
---|---|
static THROW_IF_NOT_FOUND: THROW_IF_NOT_FOUND | |
static NULL: Injector |
静态方法
从 v5 开始使用新的签名 Injector.create(options) Deprecated from v5 use the new signature Injector.create(options) 参数
返回值 | ||||||
创建一个新的注入器实例,该实例会根据指定的类型或 Creates a new injector instance that provides one or more dependencies, according to a given type or types of
参数
返回值新的注入器实例。
|
方法
根据提供的令牌从注入器中检索实例。 Retrieves an instance from the injector based on the provided token. | |||||||||
参数
返回值注入器的实例(如果已定义),否则为
异常
当 | |||||||||
使用说明
以下示例创建一个服务注入器实例。
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);