【问题标题】:Angular 11: inject service into a passed functionAngular 11:将服务注入传递的函数
【发布时间】:2021-07-26 21:07:50
【问题描述】:

假设我有模型类:

export class Model {
  id: number;
  editAction?: () => any;
}

然后某些组件创建具有定义函数的对象的数组

  someArray: Model[];

  constructor(private readonly injectedService: InjectedService) {}

  private createObjects(): void {
    this.someApiService.getData().subscribe((data) => {
    this.someArray = data.map(x => 
      ({id: x.id, editAction: someEditAction})
    );
  }

  private someEditAction(): void {
    this.injectedService
      .open(/* ... */)
  }

然后通过@Input() 获得someArray 的另一个组件尝试为HTML 中的每个元素调用editAction(一切正常):

模板:

<div *ngFor="let item of someArray">
  <button (click)="item.editAction()">
</div>

Component:
@Input() someArray: Model[];

问题是当我们点击这个按钮后,函数“someEditAction”实际上被调用了,但是它没有依赖于它的第一个组件并且它抛出了injectService为null的错误。有没有办法将此服务注入该功能? InjectedService 当然像往常一样用providedIn: 'root' 装饰。我尝试构建 factoryProvider,但我认为我做错了

【问题讨论】:

标签: angular dependency-injection


【解决方案1】:

而不是这个:

({id: x.id, editAction: someEditAction})

这样写:

({id: x.id, editAction: () =&gt; this.someEditAction()})

这将保持正确的this

编辑:话虽如此,应该考虑按照@DeborahK 上述评论的精神进行设计更改。

【讨论】:

  • 晚上是为了睡觉,而不是编码,这是有原因的。非常感谢!
猜你喜欢
  • 2020-11-21
  • 2014-05-18
  • 1970-01-01
  • 2021-11-13
  • 1970-01-01
  • 2021-06-07
  • 2017-08-24
  • 2019-09-10
相关资源
最近更新 更多