I'm trying to understand why when I transform the observable it comes up undefined in the console log even though I know it has values assigned to it.
Http Request
getLibraryCardPeople(bookName: String): Observable<people[]> {
return this.http.get<LibraryCard>(url).pipe(map(results => results.people));
}
JSON response
book : "LOTR"
people : [
{"name" : "joe", "age" : 20 , "Location": [...]},
{"name" : "sarah", "age" : 16 , "Location": [...]}
]
When I execute the function and try and observe the people array is always undefined in the console log. However, If I don't map, I can see the entire JSON Response is defined.
CodePudding user response:
You need to subscribe
to the httpClient. First subscribe
will activate the http call so to say.
getLibraryCardPeople(bookName: String): Observable<people[]> {
return this.http.get<LibraryCard>(url);
}
Then in your component:
this.myService.getLibraryCardPeople.subscribe(data => {
data.pipe(map(results => results.people));
})
This is the normal way to use HttpClient
. What you can do, too, is to use toPromise
from RxJS
. Read all about here. A example:
this.http.get<LibraryCard>(url).toPromise()
.then(res => console.log(res))
.catch(err => { console.log ('error');