【问题标题】:http json data prints to console but not to page in Ionic 3http json 数据打印到控制台但不打印到 Ionic 3 中的页面
【发布时间】:2023-03-22 03:32:01
【问题描述】:

我知道这可能是一个简单的解决方案。我正在构建一个 Ionic 3 应用程序,并且能够连接到 json 数据文件并将对象打印到控制台,但我无法将 item 传递给我的搜索功能。我在页面上遇到的错误是 Runtime Error - Cannot read property "filter" of undefined - 我猜是因为该项目不可用。

data.ts

import { Injectable } from "@angular/core";
import { Http } from "@angular/http";
import "rxjs/add/operator/map";

@Injectable()
export class Data {
  items: any;

  constructor(public http: Http) {
    this.http
      .get("./assets/data/plaques.json")
      .map(res => res.json())
      .subscribe(data => {
        this.items = data;
        console.log(data);
      });
  }

  filterItems(searchTerm) {
    return this.items.filter(item => {
      return (
        item.veteran_first.toLowerCase().indexOf(searchTerm.toLowerCase()) > -1
      );
    });
  }
}

【问题讨论】:

    标签: javascript json angular ionic-framework ionic3


    【解决方案1】:

    您正在尝试在 this.items 初始化之前访问它。

    http.get是一个异步函数,访问filterItems时可能没有设置this.items

    我强烈推荐阅读this question/answer,这将有助于更好地理解 javascript 的异步特性。

    【讨论】:

    【解决方案2】:

    你能用zone()这样包装吗:

    this.zone.run(() => {
       this.items = data;
     });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-05-11
      • 2020-10-10
      • 2012-02-07
      • 2015-05-04
      • 2016-11-19
      • 2018-07-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多