簡體   English   中英

Angular 2不顯示HTTP數據

[英]Angular 2 not displaying data from HTTP

我正在使用Angular 2執行HTTP請求,但未顯示結果。 我有以下服務:

getData() {
  return this.http.get(this.api)
    .toPromise()
    .then(response => response.json())
    .catch(this.handleError);
}

這是我的AppComponent

info: any;
error: any;

constructor(private appService: AppService) {}

getData() {
  this.appService
    .getData()
    .then(response => this.info = response)
    .catch(error => this.error = error);
}

ngOnInit() {
  this.getData();
}

在我的模板上,我正在調用{{info.fields.id}}但它給了我一個錯誤: ORIGINAL EXCEPTION: TypeError: Cannot read property 'data' of undefined

關於我在做什么錯的任何提示嗎?

我還創建了一個Plunker來重現此問題。

嘗試在模板中使用安全導航(Elvis)運算符,例如fruit: {{info?.data?.fruit}} 您可以在此處找到有關安全操作員的更多信息

這是必需的,因為您的服務正在兌現承諾。 在控制器的getData()方法中,您正在使用該諾言,並通過.then()在控制器上設置info屬性。 問題在於視圖在您的諾言完全解決之前就已呈現。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM