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.