离子读取本地JSON文件

时间:2019-01-02 21:54:36

标签: json angular ionic-framework

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

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

getProducts(){     console.log('Inside 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返回:未定义

您能建议我哪里出问题了吗?

3 个答案:

答案 0 :(得分:1)

将<< strong>文件名>。json文件放入资产文件夹,并将请求更改为以下内容,

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);

答案 1 :(得分:0)

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

yourPage.ts

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

要调用它:

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

答案 2 :(得分:0)

最简单的方法是使用 fetch()这样的功能:

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