使用Array或QueryList来保存服务中的组件列表?

问题描述 投票:0回答:1

我创建了一个PopupService,如下所示:

export class PopupService {

  popups: PopupComponent[] = [];

  open(popup: PopupComponent) {
    this.popups.forEach(popup => popup.active = false);
    popup.active = true;
  }

  close(popup: PopupComponent) {
    popup.active = false;
  }  

}

弹出窗口应该是QueryList而不是Array吗?

popups: QueryList<PopupComponent>;

PopupComponent如下:

export class PopupComponent implements OnInit {

  @Input() active: boolean = false;

  constructor(public popupService: PopupService) { }

  ngOnInit() {
    this.popupService.popups.push(this);
  }

  close() {
    this.popupService.close(this);
  }

  toggle() {
    if (this.active)
      this.popupService.close(this);
    else
      this.popupService.open(this);
  }

}
angular angular-services
1个回答
2
投票

简短:对于您的用例,一个简单的数组就足够了

Long:你不应该在你的用例中使用QueryList<T>有两个原因记录in the docs

  1. 它是一个不可变列表的抽象,所以你不能做像this.popupService.popups.push(this);这样的东西。您可以通过调整服务的API来克服这个问题。
  2. 它应该存储由ViewChildrenContentChildren提供的参考,你不使用它。所以基本上,角度应该负责管理它的实例,而不是你。这是我回答的主要原因。
© www.soinside.com 2019 - 2024. All rights reserved.