Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

rxjs - angular 11 handle http response

Guess this might be basic but I'm a complete angular and observable beginner. Trying to follow the angular official Heroes tutorial which in the end uses an in-memory api to mock a real server; I am hooking my example with a real backend but unsure how to handle the data returned from the server properly.

I have a HeroService, there is a method to get all heroes. I am using angular's HttpClient and by design my server returns a single object with a results property, which itself is an array. How can I convert the results property in the response to an Observable of Hero[]? By the way, each element in results property has the same shape as the defined Hero interface.

getHeroes(): Observable<Hero[]> {
    var res: Hero[] = []
    return this.http.get("https://my_heroes_url", this.httpOptions)
            .pipe(x => x['results'] as Hero[]);
    
  }
question from:https://stackoverflow.com/questions/65895396/angular-11-handle-http-response

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Use the map RxJS operator:

import { map } from 'rxjs/operators';

getHeroes(): Observable<Hero[]> {
  return this.http.get("https://my_heroes_url", this.httpOptions)
            .pipe(map(x => x['results'] as Hero[]));
}

For more information about RxJS operators, consider taking a look at the RxJS manual on operators.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...