![](/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.