0

I have tried to get data from assets/data/people-data.json in Ionic. In my providers/people-data.ts

getLocalData(){
 try{
  this.http.get('assets/data/people-data.json').map(res => res.json()).subscribe(data => {
   return data;
  });
 }
  catch (error) {
   console.log("Error in httprequest");
   return this.data;
 }
 return this.data;
}

In my search.ts page(where I need the data to be published) the code is as follows

generateData() {
 try {
  this.peopleData.getLocalData().then((result) =>{
   console.log("data recieved")
  });
} catch (error) {
   console.error("Couldnot fetch data",error);
  }
}

1 Answers1

1

This is because getLocalData should return a Promise but its actually returning undefined (or whatever this.data is, at the start of getLocalData).


Following will work fine. Here, getLocalData returns an observable and generateData subscribes to it.

getLocalData(){
    return this.http.get('assets/data/people-data.json').map(res => res.json())
}

generateData(){

    this.peopleData.getLocalData().subscribe(
        (result) =>{
        console.log("data recieved")
    }, (err)=>{
            console.log("Error in httprequest");
        }
    );
}


Problem in your code:

Observables and Promises are two patterns used to deal with asynchronous code (Others are: callbacks, asyn-await).

An Observable and Promise, both are Javascript Object. Both are like a proxy for a value which will be arriving later in time. When the value has arrived (its called resolved value), you use .subscribe() if you are extracting resolved value from Observable but .then() if you are using extracting resolved value from Promise.

In your case this.http.get('assets/data/people-data.json') returns an Observable. Also this.http.get('assets/data/people-data.json').map(res => res.json()) returns modified Observable. But you trying to use .then() to extract it, which is not correct.

Also, you were returning, observable.map().subscribe() which does Not return an Observable, rather a subscription Object. This is a common gotcha by beginners.

Promises and Observables are deceptively similer. Better to learn them to some extent before using in your code.

dasfdsa
  • 7,102
  • 8
  • 51
  • 93