繁体   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