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
316 views
in Technique[技术] by (71.8m points)

angular - Get rid of subscriptions in subscriptions

I try to understand what RxJS flatMap does to get rid of a subscription in another subsription:

this.http.get<IFilm>(`https://swapi.dev/api/films/${id}/`).subscribe(res => {
  this.film = res;
  this.film.characters.map((url: string) => {
    this.http.get<IActor>(url).subscribe(res => {
      this.name = res;
      this.NameList.push(this.name)
    })
  })

});

What would be a good way to resolve this? Is it possible to do this in a method or should I use 2 for example or pipes like here:

https://stackblitz.com/edit/angular-dlony2?file=src%2Fapp%2Fstar-wars.service.ts


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

1 Answer

0 votes
by (71.8m points)

Here I've done the RxJS thing of not putting any side effects into your transformations/data pipeline and saving them all for the end consumer (subscribe).

This should make it much easier to test, extend, and maintain your code.

Typically your end consumer should be the UI or a database of some sort. There's rarely a reason to have your end consumer just set a global variable, but that's where I left it for now.

this.http.get<IFilm>(`https://swapi.dev/api/films/${id}/`).pipe(  
  map(film => ({
    film,
    nameCalls: film.characters.map(
      url => this.http.get<IActor>(url)
    )
  })),
  mergeMap(({film, nameCalls}) => forkJoin(nameCalls).pipe(
    map(names => ({film, names}))
  ))
).subscribe(({film, names}) => {
  this.film = film;
  this.nameList = names;
});

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

...