2017-04-20 54 views
0

tutorial具有在HTTP部分下面的行: 打字稿铸造JSON来在角对象使用`as`不起作用

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

得到时英雄。 response.json().data返回以下内容: enter image description here

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

export class MyClass { 
    name: string; 
} 

response.json()从服务器返回查找方式如下: enter image description here

所以我尝试做的是:

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}},那么就没有错误,并从服务器的应答,我必须从服务器[对象的对象]印刷响应。

所以问题是我的代码和角度教程有什么区别?我已经看到很多回答问题,比如How do I initialize a typescript object with a JSON object,但是我希望它只需使用as关键字就容易多了。

+0

请阅读标签说明,不使用角2+问题angularjs标签。 – estus

回答

3

这与TypeScript无关。

Error: Cannot read property 'name' of undefined.

是运行时错误。

从引导的示例使用指令作为保障措施:

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

虽然上面的代码没有。

myObject是原本undefined,没有什么阻止由编译器解析{{myObject.name}}表达,因此错误。 Safe navigator operator(被称为猫王运营商)应该用来避免这种情况:

{{myObject?.name}}