@Self 和 @Host Angular 2+ 依赖注入装饰器之间的区别 [英] Difference between @Self and @Host Angular 2+ Dependency Injection Decorators

查看:21
本文介绍了@Self 和 @Host Angular 2+ 依赖注入装饰器之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请解释一下@Self 的区别@主机.

angular API 文档给出了一些想法.但我不清楚.为 Self 提供的示例使用 ReflectiveInjector 来举例说明用法.

The angular API documentation gives some idea. But it's not clear to me. The example provided for Self uses ReflectiveInjector to exemplify usage.

然而,人们很少会在实际应用代码中使用ReflectiveInjector(在测试中可能更多).你能举个例子说明你会在哪里使用@Selfcode> 代替 @Host 在此类测试场景之外??

However, one would rarely, if ever, use ReflectiveInjector in actual app code (probably more in testing).. Can you give an example of where you would use @Self instead of @Host outside of such test scenarios??

推荐答案

tl;dr

看起来当使用 @Self 时,Angular 只会为该指令/组件所在的元素查找组件注入器上绑定的值.

tl;dr

It looks like when @Self is used, Angular will only look for a value that is bound on the component injector for the element that this Directive/Component exists on.

看起来当使用 @Host 时,Angular 将查找绑定在该指令/组件所在元素的组件注入器或父组件.Angular 将此父组件称为主机".

It looks like when @Host is used, Angular will look for a value that is bound on either the component injector for the element that this Directive/Component exists on, or on the injector of the parent component. Angular calls this parent component the "host".

虽然主要描述不是很有帮助,但它看起来像 @Self<文档中的示例/a> 和 @Host 在阐明它们的使用方式和区别方面做得不错(复制如下).

Although the main descriptions aren't very helpful, it looks like the examples in the documentation for @Self and @Host do a decent job of clarifying how they are used and what the difference is (copied below).

当试图理解这一点时,记住当 Angular 依赖注入试图解析构造函数的特定值时,它首先在注入器中查找当前组件,然后向上迭代父注入器,这可能会有所帮助.这是因为 Angular 使用分层注入器并允许从祖先注入器继承.

When trying to understand this, it might help to remember that when Angular dependency injection tries to resolve a particular value for a constructor, it starts by looking in the injector for the current component, then it iterates upward through parent injectors. This is because Angular uses hierarchical injectors and allows for inheritance from ancestor injectors.

因此,当 @Host 文档说它指定注入器应该从任何注入器检索依赖项,直到到达当前组件的宿主元素",这意味着它停止了这种向上迭代一旦到达绑定到父组件的注入器,就尽早.

So when the @Host documentation says that it "specifies that an injector should retrieve a dependency from any injector until reaching the host element of the current component", that means that it stops this upward iteration early once it reaches the injector bound to the parent component.

class Dependency {}

@Injectable()
class NeedsDependency {
  constructor(@Self() public dependency: Dependency) {}
}

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

expect(nd.dependency instanceof Dependency).toBe(true);

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

@Host 示例()

class OtherService {}
class HostService {}

@Directive({selector: 'child-directive'})
class ChildDirective {
  logs: string[] = [];

  constructor(@Optional() @Host() os: OtherService, @Optional() @Host() hs: HostService) {
    // os is null: true
    this.logs.push(`os is null: ${os === null}`);
    // hs is an instance of HostService: true
    this.logs.push(`hs is an instance of HostService: ${hs instanceof HostService}`);
  }
}

@Component({
  selector: 'parent-cmp',
  viewProviders: [HostService],
  template: '<child-directive></child-directive>',
})
class ParentCmp {
}

@Component({
  selector: 'app',
  viewProviders: [OtherService],
  template: '<parent-cmp></parent-cmp>',
})
class App {
}

使用@Self 的例子很重要

假设您有一个用于修改多种类型组件行为的指令;也许这个指令提供了某种配置支持.

Example of when using @Self is important

Let's say you have a directive that is used to modify the behavior of many types of components; maybe this directive provides some sort of configuration support.

此指令绑定到整个应用程序中的许多组件,并且此指令绑定其 providers 列表中的某些服务.想要使用此指令动态配置自己的组件将注入它提供的服务.

This directive is bound to many components throughout your app and this directive binds some service in its providers list. Components that want to use this directive to dynamically configure themselves will inject the service it provides.

然而,我们要确保一个组件只使用它自己的配置,并且不会意外地注入用于某些父组件的配置服务.所以我们使用 @Self 装饰器告诉 Angular 的依赖注入只考虑在这个组件的元素上提供的配置服务.

However, we want to make sure that a component only uses its own configuration, and doesn't accidentally inject the configuration service that was meant for some parent component. So we use the @Self decorator to tell Angular's dependency injection to only consider the configuration service provided on this component's element.

这篇关于@Self 和 @Host Angular 2+ 依赖注入装饰器之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆