簡體   English   中英

離子模板中的 var 未定義,但 console.log 顯示它

[英]var in ionic template undefined, but console.log displays it

我從離子模板中的調用中得到一個未定義的錯誤:

錯誤類型錯誤:“this.x 未定義”

但是當我將 this.x 登錄到控制台時,它看起來很好。

也許這是一個簡單的問題,但我剛剛開始學習這個。 如果有人可以提供幫助,將不勝感激:)

this.http.get('xy.json', {responseType: 'text'})
    .subscribe(response => {
      this.x = JSON.parse(response);
      console.log(this.x);
});

getCurrentObj() {
    return this.x[0];
}

模板: {{ getCurrentObj().text }}

傑森:

{
    "0": {
        "text"    : "This is sample text 1",
        "type"    : "xy"
    }
}

來自 console.log 的 this.x:

Object(1)
​
0: Object { text: "This is sample text 1", type: "xy", … }
​
<prototype>: Object { … }

主要問題是您正在嘗試呈現尚未加載的數據。

subscribe()是一個異步函數,所以你必須等待那里的數據。 有兩種方法可以做到。

  1. 將您的{{ getCurrentObj().text }}包裹到<ng-container *ngIf="x"></ng-container> => <ng-container *ngIf="x">{{ getCurrentObj().text }}</ng-container>
  2. 您可以從執行get請求的函數返回一個 Observable,然后將它與模板中的async管道一起使用 =>

成分:

getCurrentObj(): Observable<CORRECT_INTERFACE_HERE> {
    return this.http.get('xy.json', {responseType: 'text'});
}

模板:

{{ (getCurrentObj() | async)?.text }}

另一件事是你不需要JSON.parse(response)因為httpClient為你做。

你應該像這樣顯示數據

get getCurrentObj() {
    return this.x[0];
}

然后在你的模板中

{{getCurrentObj}}

暫無
暫無

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

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