0

I was working with the Tour of Heroes example on the angular site (https://angular.io/tutorial/toh-pt4) and I'm having problems with the service call resolving my page object. If I call the mocked object directly everything works fine(return MOCKEDOBJECT) but when I try to use the response I keep getting the error cannot read property of undefined. I'm very new to angular and I'm just not seeing what I'm doing wrong.

Here's the service code:

getEmployer(): Promise<Employer> {
    return Promise.resolve(EMPLOYER);//doesn't work
}

getMockEmployer(): Employer {
    return EMPLOYER; //works fine
}

here's what's in my page code:

 //mocked promise - doesn't work
this.employerService.getEmployer().then(employer => this.employer = employer);

//mocked data - works fine. 
//this.employer = this.employerService.getMockEmployer(); 

FYI, my npm folder has a referenced to @angular/core(4.1.2)

I'm not doing an api call yet. I'm still working with mocked data from within the service. I'm not seeing any difference between the sample that exists in Tour of Heros and my code, but theirs works and mine doesn't.

georgeawg
  • 48,608
  • 13
  • 72
  • 95
Mykal73
  • 478
  • 4
  • 6
  • 18
  • 5
    Possible duplicate of [Response of Http Api call promise is undefined - Angular 2](https://stackoverflow.com/questions/45328860/response-of-http-api-call-promise-is-undefined-angular-2) – k11k2 Jul 27 '17 at 15:23
  • where do you try and **use the response** ? – AT82 Jul 27 '17 at 16:19
  • in my html template like {{employer.name}} – Mykal73 Jul 27 '17 at 16:22
  • Then your question is actually a dupe of this :) https://stackoverflow.com/questions/41242793/angular2-error-typeerror-cannot-read-property-of-undefined – AT82 Jul 27 '17 at 16:23
  • 1
    And as to why the TOH works, is because their response is an array, you are getting an object, which you are trying to read property paths when `employer` is still undefined. – AT82 Jul 27 '17 at 16:26
  • Ok, that's what I wasn't understanding! Thanks for your help! – Mykal73 Jul 27 '17 at 16:31
  • You're welcome :) One thing I can also point out, if you do not have deeper nested objects, you can also simply overcome this problem with initializing employer as an empty object `employer = {}` So now when it's trying to read `name` property it will not throw that error, since now it's no longer `undefined`, but an empty object :) – AT82 Jul 27 '17 at 17:51

1 Answers1

0

To help anyone who comes across this

"And as to why the TOH works, is because their response is an array, you are getting an object, which you are trying to read property paths when employer is still undefined."

Basically, make sure you're using *ngIf if you're using an object for data and not an array of objects.

Mykal73
  • 478
  • 4
  • 6
  • 18