Search code examples
javascriptangularangular-services

use Angular6 Service constructor to initialize private attribute


I'm trying to initialize a few objects in a Angular6 Service but I'm getting an error explaining that one of my private attribute is undefined.

At first I tried that :

private mockIncident: Incident[];

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

But i got the error telling that mockIncident is not defined.
ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'push' of undefined.

And then tried that :

public mockIncident: Incident[];

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


Solution

  • public mockIncident: Incident[]; is declaring an undefined object.

    Do this public mockIncident: Incident[] = [] so there is an array initialization. Here you will have all the property of an array like push()