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:
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:
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.