@Self() 解析修饰符在Angular中的用途是什么?

huangapple go评论59阅读模式
英文:

What is the use of @Self() resolution modifier in Angular?

问题

Angular文档中提到Self是“用于构造函数参数的参数装饰器,告诉DI框架从本地注入器开始解析依赖关系”。

如果我有一个组件如下所示

@Component({
  selector: 'app-foo',
  templateUrl: './foo.component.html',
  styleUrls: ['./foo.component.scss'],
  providers: [BarService],
})
export class FooComponent {
  constructor(public barService: BarService) {}
}

尽管我在根注入器中提供了BarService,但FooComponent将注入自己的服务实例,因为它在组件的提供者列表中。而且它可以在没有@Self() 的情况下工作。

显然,我缺少了一些东西,因为我无法想象在哪种情况下可以使用@Self()

我已经阅读了很多关于解析修改器的文章,但仍然不清楚@Self() 的用例是什么。

英文:

Angular docs say that Self is Parameter decorator to be used on constructor parameters, which tells the DI framework to start dependency resolution from the local injector.

If I have a component like this

@Component({
  selector: 'app-foo',
  templateUrl: './foo.component.html',
  styleUrls: ['./foo.component.scss'],
  providers: [BarService],
})
export class FooComponent {
  constructor(public barService: BarService) {}
}

Though I provided BarService in root injector, FooComponent will inject its own instance of service because it's in the Components providers list. And it will work without @Self().

Clearly, I'm missing something because I can't imagine in which scenarios @Self() can be used.

I've read numerous articles on resolution modifiers but still, it is not clear to me what are the use cases of @Self()

答案1

得分: 1

@Self() 表示组件需要提供自己的实例。

当你使用 @Self 时,即使根注入器有一个引用,如果组件没有提供自己的服务实例,就会抛出异常。

这是为了确保实例不依赖于父级。

英文:

@Self() means the component need to provide it's own instance.

When you have @Self, even if the root injector has a reference, an exception will be thrown is the component doesn't provide its own instance of the service.

This is to ensure that instance does not depend from the parents.

huangapple
  • 本文由 发表于 2023年3月9日 23:04:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/75686407.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定