繁体   English   中英

Typescript使用`as`将json强制转换为角度对象

[英]Typescript casting json to object in angular using `as` doesn't work

Angular 教程的HTTP部分中包含以下行:

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

当英雄。 response.json().data返回以下内容: 在此处输入图片说明

我试图做同样的事情。 我在服务器端使用Django,并使用rest_framework返回json。 在Angular中,我有我的课程:

export class MyClass {
  name: string;
}

从服务器返回的response.json()如下所示: 在此处输入图片说明

所以我想做的是:

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);
}

我的模板包含:

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

我得到错误:无法读取未定义的属性“名称”。

当我将html {{myObject.name}}更改为{{myObject}} ,就没有错误,并且来自服务器的响应以及我已打印了来自服务器[object Object]的响应

所以问题是我的代码和角度教程有什么区别? 我已经看到了很多已回答的问题,例如如何使用JSON对象初始化打字稿对象 ,但我希望仅使用as关键字会更容易。

这与TypeScript无关。

错误:无法读取未定义的属性“名称”。

是运行时错误。

本指南中的示例使用指令作为安全措施:

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

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

虽然上面的代码没有。

如果最初undefined myObject ,则不会阻止编译器解析{{myObject.name}}表达式,因此会出现错误。 应使用安全的导航员操作员 (称为猫王操作员)避免这种情况:

{{myObject?.name}}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM