[英]Typescript casting json to object in angular using `as` doesn't work
Angular tutorial has the following line in the HTTP section: Angular 教程的HTTP部分中包含以下行:
response => response.json().data as Hero
when getting hero. 当英雄。
response.json().data
returns the following: response.json().data
返回以下内容:
I tried to do the same thing. 我试图做同样的事情。 I used Django on server side and return json using rest_framework .
我在服务器端使用Django,并使用rest_framework返回json。 In Angular i have my class:
在Angular中,我有我的课程:
export class MyClass {
name: string;
}
response.json()
returned from server looks the following way: 从服务器返回的
response.json()
如下所示:
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. 当我将html
{{myObject.name}}
更改为{{myObject}}
,就没有错误,并且来自服务器的响应以及我已打印了来自服务器[object Object]的响应 。
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. 我已经看到了很多已回答的问题,例如如何使用JSON对象初始化打字稿对象 ,但我希望仅使用
as
关键字会更容易。
This has nothing to do with TypeScript. 这与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. 如果最初
undefined
myObject
,则不会阻止编译器解析{{myObject.name}}
表达式,因此会出现错误。 Safe navigator operator (known as Elvis operator) should be used to avoid this: 应使用安全的导航员操作员 (称为猫王操作员)避免这种情况:
{{myObject?.name}}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.