简体   繁体   English

如何避免嵌套订阅 rxjs?

[英]How can I avoid nested subscribe in rxjs?

I have an code with nested subscribes:我有一个嵌套订阅的代码:

      .subscribe((data) => {
        const { game, prizes } = data;
        this.ticketService.setListOfTickets(game.tickets);
        this.ticketService.getListOfTickets().subscribe((data: any) => {
          this.listOfTickets = data;
        });
        this.game = game;
        this.type = game.type;
        this.combinations = prizes.map((el: Prize) => el.patterns).flat();
      });

How can i improve this code to avoid nested subscription?我如何改进此代码以避免嵌套订阅?

.pipe(
    switchMap(data => {
      this.ticketService.setListOfTickets(data.game.tickets);
      return this.ticketService.getListOfTickets().pipe(
        map(listOfTickets => ({ ...data, listOfTickets }))
      );
    })
)
.subscribe(({ game, prizes, listOfTickets }) => {
    this.listOfTickets = listOfTickets;
    this.game = game;
    this.type = game.type;
    this.combinations = prizes.map((el: Prize) => el.patterns).flat();
});

switchMap takes the result of the firstCall and uses the result to switch to an inner observable. switchMap 获取 firstCall 的结果并使用该结果切换到内部可观察对象。

You can use forkJoin and join multiple calls into single subscription.您可以使用 forkJoin 并将多个调用加入单个订阅。 From your code is not visible the name of the function that are you subscribing on, so I just used name: gameService.getGames()从您的代码中看不到您订阅的 function 的名称,所以我只使用名称: gameService.getGames()

forkJoin([this.gameService.getGames(),this.ticketService.getListOfTickets()]).subscribe((data) => {
        const { game, prizes } = data[0];
        this.ticketService.setListOfTickets(game.tickets);
        this.listOfTickets = data[1];
        this.game = game;
        this.type = game.type;
        this.combinations = prizes.map((el: Prize) => el.patterns).flat();
      });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM