Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ionic read local JSON file

I am trying to read a local JSON file in Ionic 3. I have saved the JSON file in assets folder as csvjson.json

I call the following function inside one of the services.

getProducts() { console.log('Inside getProducts')

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

}

and then store the result in

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

However I get the output as

Returned from getProducts:undefined

Can you pls suggest where I am going wrong?

like image 217
shubham Avatar asked Apr 10 '26 09:04

shubham


1 Answers

Put the <file-name>.json file in assets folder and change the request to following,

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

Component file

this.databaseprovider.getProducts().then((result)=>{
   myArray = result;
});
console.log("Returned from getProducts:" + myArray.length);
like image 53
manish kumar Avatar answered Apr 12 '26 21:04

manish kumar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!