![](/img/trans.png)
[英](Angular2) JSON data (http.get()) is undefined, and data is not updated in the component
[英]JSON data loaded from http.get() is undefined in my Angular 2 template
我正在尝试读取本地json文件并将其解析为我制作的具有相同属性的类。 当我尝试从类中读取时,它给出了错误,表示该类为null或未定义。
我有一个文件hall.ts
,看起来像这样:
import {Item} from '../item/item';
export class Hall {
constructor(public id:number,
public naam:string,
public oppervlakte:number,
public aantalItems:number,
public itemsMetNodigeActie:number,
public items:Item[]) {
}
}
它使用item.ts
:
export class Item {
constructor(public categorie:string,
public naam:string,
public productnummer:string,
public omschrijving:string,
public laatsteUitgevoerdeActie:Actie,
public eerstVolgendeActie:Actie) {
}
}
export class Actie{
constructor(datum: string,
type: string,
omschrijving: string){}
}
我试图读取的json文件hall1.json
看起来像这样:
{
"id": 1,
"naam": "hall1",
"oppervlakte": 100,
"aantalItems": 3,
"itemsMetNodigeActie": 3,
"items": [
{
"id": 1,
"categorie": "machine",
"productnummer": "ADE124e",
"omschrijving": "print papieren af",
"laatsteUitgevoerdeActie": {
"datum": "2015-01-05T00:00:00.000Z",
"type": "vervanging",
"omschrijving": "papier vervangen"
},
"eerstVolgendeActie": {
"datum": "2016-01-06T00:00:00.000Z",
"type": "vervanging",
"omschrijving": "inkt vervangen"
}
}
]
}
我正在使用hall.service.ts
尝试读取本地存储的json文件,并将其返回到Hall
对象中。 这是这样做的方法:
public getHall(): Observable<Hall> {
return this.http.get('app/hall/hall1.json')
.map((res:Response) => res.json());
}
我在hallDetail.component.ts
使用此方法
export class HallDetailComponent implements OnInit{
public hall: Hall;
constructor(
private service: HallService
){}
ngOnInit(){
this.service.getHall().subscribe((hall:Hall) => {
this.hall = hall;
})
}
}
到目前为止,它并没有给我任何错误,但是当我尝试从hall
对象中读取时,它是未定义的
@Component({
template: `
<div>
{{hall.naam}}
</div>
`
})
错误:
EXCEPTION: TypeError: Cannot read property 'naam' of undefined in [
{{hall.naam}}
in HallDetailComponent@1:7]
您必须记住http.get()
调用是异步的。 在您的异步http调用解析之前,您的模板正在尝试将hall
作为对象进行处理。
这就是为什么hall
未定义的原因,因此,您无法访问它上面的任何属性(它尚不存在)。
正如Eric在评论中提到的那样,为你的模板尝试这样的事情:
@Component({
template: `
<div>
{{hall?.naam}} <!-- note the added ? -->
</div>
`
})
这将使hall
null上的naam
参考安全。
更新:
为了完整起见,我会指出你实际上也可以使用* ngIf,尽管null安全检查可以使模板看起来更整洁。
@Component({
template: `
<div *ngIf="hall"> <!-- note the added *ngIf -->
{{hall.naam}}
</div>
`
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.