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

Use Array or QueryList to hold a list of Components in a Service?

我创建了一个 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 而不是数组吗?

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);
  }

}

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

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

  1. 它是一个不可变列表的抽象,所以你不能做像this.popupService.popups.push(this);这样的事情。您可以通过调整服务的 api 来克服这个问题。

  2. 它应该存储 ViewChildren 提供的引用和 ContentChildren,您没有使用。所以基本上,angular 应该负责管理它的实例,而不是你。这是我回答的主要原因。