1

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]))
    } 
  }
NeitoFR
  • 716
  • 1
  • 11
  • 23

2 Answers2

3

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()

Axiome
  • 695
  • 5
  • 18
  • For info ngOnInit doesn't work on services : "Lifecycle hooks, like OnInit() work with Directives and Components. They do not work with other types, like a service in your case." [link](https://stackoverflow.com/a/35110798/9243790), but the problem was that I didn't init the array to [], thanks – NeitoFR Feb 28 '20 at 14:06
  • My bad, I read wrongly your post on the type of angular component you are declaring. I'm updating my response, to correct my answer that was very misleading. I apologize – Axiome Feb 28 '20 at 14:07
2

mockIncident array is not initialized, add = [];

private mockIncident: Incident[] = [];
porgo
  • 1,729
  • 2
  • 17
  • 26