我想學習角2,我無法得到最簡單的http上班。Angular 2簡單HTTP獲取
我得到的運行時錯誤
Cannot read property 'id' of undefined
但在同一時間被其迷惑了我很多的頁面上顯示「身份證」的價值。它怎麼可能是未定義的並且仍然顯示。
我從的WebAPI返回此JSON
{
"category":["some string"],
"icon_url":"some string",
"id":"some string",
"url":"some string",
"value":"some string"
}
我已經創建了一個接口
export interface IProduct {
category: string;
icon_url: string;
id: string;
url: string;
value: string;
}
在我的服務,我有這個方法調用的WebAPI,並返回JSON
getproducts(context: ContentAndStructureContext): Observable<IProduct[]> {
return this.http.get(routes.url(context), { cache: true })
.map((res: Response) => <IProduct[]>res.json())
.do(data => console.log(data));
}
工作正常,數據對象正在記錄到控制檯。到目前爲止好
在我的組件我有打電話的getProducts方法
export class HomeComponent implements OnInit {
isProductLoading: boolean;
iproducts: IProduct[];
constructor(private contentAndStructureService: ContentAndStructureService) {}
ngOnInit() {
this.isLoading = true;
this.isProductLoading = true;
this.contentAndStructureService.getproducts({ category: 'dev' })
.pipe(finalize(() => { this.isProductLoading = false; }))
.subscribe(iproducts => this.iproducts = iproducts);
}
}
這是我的HTML。它打印iproducts.id的值就好了。
<div class="container">
<mat-card>
<mat-card-content>
<mat-card-subtitle>
<app-loader [isLoading]="isProductLoading" size="1.5"></app-loader>
<q [hidden]="isProductLoading">{{iproducts.id}}</q>
</mat-card-subtitle>
</mat-card-content>
</mat-card>
</div>
但在控制檯中的跟隨誤差得到記錄
ERROR TypeError: Cannot read property 'id' of undefined
at Object.eval [as updateRenderer] (home.component.html:13)
at Object.debugUpdateRenderer [as updateRenderer] (core.js:14377)
at checkAndUpdateView (core.js:13513)
at callViewAction (core.js:13858)
at execComponentViewsAction (core.js:13790)
at checkAndUpdateView (core.js:13514)
at callViewAction (core.js:13858)
at execEmbeddedViewsAction (core.js:13816)
at checkAndUpdateView (core.js:13509)
at callViewAction (core.js:13858)
我不明白的ID如何能不確定,並在同一時間的價值得到印刷就好了......我不知道如何解決它。我花了數不清的時間,希望有人有時間讓我看看我在這裏做錯了什麼。
默認值謝謝。它有助於設定一個默認值。當然:) –
很高興我能幫上忙! – raykrow