【问题标题】:var in ionic template undefined, but console.log displays it离子模板中的 var 未定义,但 console.log 显示它
【发布时间】:2019-08-16 10:12:18
【问题描述】:

我从离子模板中的调用中得到一个未定义的错误:

ERROR TypeError: "this.x is undefined"

但是当我将 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 }}

json:

{
    "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 { … }

【问题讨论】:

    标签: javascript angular typescript ionic-framework httpclient


    【解决方案1】:

    主要问题是您正在尝试渲染尚未加载的数据。

    subscribe() 是一个异步函数,所以你必须等待那里的数据。有两种方法可以做到。

    1. {{ getCurrentObj().text }} 包裹到&lt;ng-container *ngIf="x"&gt;&lt;/ng-container&gt; => &lt;ng-container *ngIf="x"&gt;{{ getCurrentObj().text }}&lt;/ng-container&gt;
    2. 您可以从执行 get 请求的函数返回一个 Observable,然后将其与模板中的 async 管道一起使用 =>

    组件:

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

    模板:

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

    另一件事是您不需要JSON.parse(response),因为httpClient 会为您完成。

    【讨论】:

      【解决方案2】:

      你应该像这样显示数据

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

      然后在你的模板中

      {{getCurrentObj}}
      

      【讨论】:

      • 感谢提示,我会这样做的,不幸的是这并不能解决问题。
      猜你喜欢
      • 2015-06-24
      • 2014-06-08
      • 1970-01-01
      • 2018-05-28
      • 2016-11-02
      • 1970-01-01
      • 2019-12-10
      • 2020-07-03
      • 1970-01-01
      相关资源
      最近更新 更多