Angular 中的@SkipSelf 装饰器是什么?

What is @SkipSelf decorator in Angular?

@SkipSelf 装饰器告诉 DI 从父注入器开始在整棵树中寻找依赖项

我遇到了如下所示的@SkipSelf 装饰器。在这种情况下,这个 @SkipSelf 装饰器到底意味着什么?

class Dependency {}

@Injectable()
class NeedsDependency {
  constructor(@SkipSelf() public dependency: Dependency) { this.dependency = dependency; }
}

const parent = ReflectiveInjector.resolveAndCreate([Dependency]);
const child = parent.resolveAndCreateChild([NeedsDependency]);
expect(child.get(NeedsDependency).dependency instanceof Dependency).toBe(true);

const inj = ReflectiveInjector.resolveAndCreate([Dependency, NeedsDependency]);
expect(() => inj.get(NeedsDependency)).toThrowError();

让我们逐行开始:

第一种情况:

A. 创建parent injector并添加Dependency:

const parent = ReflectiveInjector.resolveAndCreate([Dependency]);

B. 创建子注入器并添加NeedsDependency,由于父注入器中提供了Dependency,DI框架可以解析[=15] =]的依赖项(Dependency

const child = parent.resolveAndCreateChild([NeedsDependency]);

第二种情况:

A. 创建一个注入器并将 DependencyNeedsDependency 添加到其中:

const inj = ReflectiveInjector.resolveAndCreate([Dependency, NeedsDependency]);

B. 这次解析NeedsDependency的依赖会失败,因为@SkipSelf()被应用到Dependency,DI框架会忽略 inj 注入器中的 Dependency 实例,并尝试查找层次结构以找到满足此不存在的依赖关系的提供者,因此 inj.get(NeedsDependency) 将抛出错误 NeedsDependency无法解析。

expect(() => inj.get(NeedsDependency)).toThrowError();