使用 Angular6 服务构造函数初始化私有属性

use Angular6 Service constructor to initialize private attribute

我正在尝试初始化 Angular6 服务中的一些对象,但我收到一条错误消息,说明我的私有属性之一未定义。

起初我试过:

private mockIncident: Incident[];

constructor() {
    this.mockIncidentRaw.forEach(incident => {
      this.mockIncident.push(new Incident().deserialize(incident))
    });
  }

但我收到错误消息,提示未定义 mockIncident。
错误错误:未捕获(承诺):TypeError:无法读取未定义的 属性 'push'。

然后试了一下:

public mockIncident: Incident[];

  constructor() {
    init();
  }
  
  init = () => {
    for(let i = 0; this.mockIncidentRaw.length; i++) {
      this.mockIncident.push(new Incident().deserialize(this.mockIncidentRaw[i]))
    } 
  }

public mockIncident: Incident[]; 正在声明一个未定义的对象。

这样做public mockIncident: Incident[] = [] 这样就有了一个数组初始化。在这里你将拥有像 push()

这样的数组的所有 属性

mockIncident数组未初始化,添加=[];

private mockIncident: Incident[] = [];