【问题标题】:Ionic read local JSON file离子读取本地 JSON 文件
【发布时间】:2019-05-29 12:48:19
【问题描述】:

我正在尝试在 Ionic 3 中读取本地 JSON 文件。我已将资产文件夹中的 JSON 文件保存为 csvjson.json

我在其中一项服务中调用以下函数。

getProducts() { console.log('内部 getProducts')

return this.http.get(this.apiHost)
  .map((response: Response) => {
    console.log(response);
    return response.json();
  });

}

然后将结果存入

myArray = this.databaseprovider.getProducts();
console.log("Returned from getProducts:" + myArray.length);

但是我得到的输出为

从 getProducts 返回:未定义

你能建议我哪里出错了吗?

【问题讨论】:

  • 从上面的代码中没有得到你到底在做什么解释更多
  • 在 http.get 中不再需要调用 map 了,因为它已经返回了一个 json。因此我使用了下面的代码。 this.http.get<any[]>('assets/csvjson.json') .subscribe(data => { data.forEach((item) => { console.log(item); console.log(item.Category);

标签: json angular ionic-framework


【解决方案1】:

将 file-name>.json 文件放入 assets 文件夹中,并将请求更改为以下,

public getProducts() { 
    return new Promise((resolve, reject) => {
        this._http.get("assets/<file-name>.json")
            .map((response: Response) => {
                console.log(response);
                resolve(response.json());
        });
    });
}

组件文件

this.databaseprovider.getProducts().then((result)=>{
   myArray = result;
});
console.log("Returned from getProducts:" + myArray.length);

【讨论】:

    【解决方案2】:

    当您在页面的 Typescript 文件中调用它时,例如在 yourPage 文件夹中调用 yourPage.ts,您可以通过 导入 来访问本地 JSON 文件:

    yourPage.ts

    import * as JSONdata from "../../assets/csvjson.json" //You can name 'JSONdata' as you want
    

    叫它:

    getProducts() {
     console.log(JSONdata);
    }
    

    【讨论】:

    【解决方案3】:

    最简单的方法是像这样使用 fetch() 函数:

        readJsonData(){    
                fetch("../../assets/data/Parameters.json").then(res=>res.json()).then(json=>{
                    console.log("OUTPUT: ", json);
                    //DO YOUR STAFF
                });
        }```
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-09-16
      • 2018-06-25
      • 2017-07-07
      • 2019-01-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多