Angular中的@SkipSelf装饰器是什么



@SkipSelf-decorator告诉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创建父注入器并将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框架将忽略inj注入器中的Dependency实例,并尝试查找层次结构以找到一个不存在的满足此依赖关系的提供程序,因此inj.get(NeedsDependency)将抛出一个错误,因为无法解析NeedsDependency

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

相关内容

  • 没有找到相关文章

最新更新