0

Angular tutorial has the following line in the HTTP section:

response => response.json().data as Hero

when getting hero. response.json().data returns the following: enter image description here

I tried to do the same thing. I used Django on server side and return json using rest_framework. In Angular i have my class:

export class MyClass {
  name: string;
}

response.json() returned from server looks the following way: enter image description here

so what i try to do is:

myObject: MyClass;

ngOnInit(): void {
    this.getResponseFromServer().then(myObject => this.myObject = myObject);
}

getResponseFromServer(): Promise<MyClass> {
    return this.http.get("http://127.0.0.1:8000/myurl/")
      .toPromise()
      .then(response => response.json() as MyClass)
      .catch(this.handleError);
}

and my template contains:

<ion-card> 
    <ion-card-header> Card Header </ion-card-header> 
    <ion-card-content>
        Response from server {{myObject.name}}
    </ion-card-content> 
</ion-card>

and i get Error: Cannot read property 'name' of undefined.

When i change in html {{myObject.name}} to {{myObject}}, then there's no error and Response from server and i have Response from server [object Object] printed.

So the question is what is the difference between my code and angular tutorial? I've seen lots of answered question like How do I initialize a typescript object with a JSON object, but i want it to be much easier with just using as keyword.

Community
  • 1
  • 1
Dmitrii Bocharov
  • 872
  • 6
  • 21

1 Answers1

3

This has nothing to do with TypeScript.

Error: Cannot read property 'name' of undefined.

is runtime error.

The example from the guide uses directives as safeguards:

<div *ngIf="hero">
  <h2>{{hero.name}} details!</h2>
  ...
</div>

and

  <a *ngFor="let hero of heroes" ...>
    <div class="module hero">
      <h4>{{hero.name}}</h4>
    </div>
  </a>

While the code above doesn't.

When myObject is originally undefined, nothing prevents compiler from parsing {{myObject.name}} expression, hence the error. Safe navigator operator (known as Elvis operator) should be used to avoid this:

{{myObject?.name}}

Estus Flask
  • 206,104
  • 70
  • 425
  • 565