Reputation: 1108
I am just getting started with Angular and its the first time I work with observables. I have gone through the Tours of Heroes tutorial on the official website and want to translate it into my application.
hero.service.ts from the tutorial has the following function:
/** GET heroes from the server */
getHeroes(): Observable<Hero[]> {
return this.http.get<Hero[]>(this.heroesUrl)
.pipe(
tap(_ => this.log('fetched heroes')),
catchError(this.handleError<Hero[]>('getHeroes', []))
);
}
I can get it to work when JSON response looks like this:
[
{
"id": 1,
"user": "admin",
"date": "2020-12-03T12:25:11Z",
"name": "Test"
},
{
"id": 2,
"user": "admin",
"date": "2020-12-03T13:34:01Z",
"name": "Test2"
}
]
But my REST API returns the following:
{
"count": 6,
"next": "http://127.0.0.1:8000/api/heroes?page=2",
"previous": null,
"results": [
{
"id": 1,
"user": "admin",
"date": "2020-12-03T12:25:11Z",
"name": "Test"
},
{
"id": 2,
"user": "admin",
"date": "2020-12-03T13:34:01Z",
"name": "Test2"
}
]
}
So my question is, how can I transform the response to extract the data from the nested results field?
I assume I have to save the response from this.http.get(this.heroesUrl) (without <Hero[]>) and then extract the 'results' section and return the observable?
Upvotes: 0
Views: 507
Reputation: 1501
change Observable<Hero[]>
to Observable<HttpResponse<Hero[]>>
in service file and subscriber as,
data: Array<Hero>;
getHeroes().subscribe(res=>{
this.data = res.results;
});
Upvotes: 0
Reputation: 83
getHeroes().subscribe(res=>{
let data = res.results;
});
or you can use RxJs map
getHeroes(): Observable<Hero[]> {
return this.http.get<Hero[]>(this.heroesUrl)
.pipe(
tap(_ => this.log('fetched heroes')),
map( data=>{
let val = data.results;
return val;
}),
catchError(this.handleError<Hero[]>('getHeroes', []))
);
}
Upvotes: 1