2

@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();
4

1 回答 1

0

让我们逐行开始:

第一种情况:

A.创建父注入器并添加Dependency到它:

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

B.创建子注入器并添加NeedsDependency到它,由于Dependency在父注入器中提供,DI框架可以解决NeedsDependency依赖关系(Dependency

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

第二种情况:

A.创建一个注入器并将Dependency&添加NeedsDependency到它:

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

B.这次解析NeedsDependency的依赖会失败,因为@SkipSelf()被应用到了Dependency,DI框架会忽略injector中的Dependency实例inj,并尝试查找层次结构来找到一个满足这个不存在的依赖的provider,因此inj.get(NeedsDependency)会抛出一个NeedsDependency无法解决的错误。

expect(() => inj.get(NeedsDependency)).toThrowError();
于 2020-12-28T17:12:35.723 回答