typescript 如何避免rxjs中的嵌套订阅?

fcg9iug3  于 2023-01-14  发布在  TypeScript
关注(0)|答案(2)|浏览(215)

我有一个嵌套订阅的代码:

.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();
      });

我如何改进这段代码以避免嵌套订阅?

kognpnkq

kognpnkq1#

.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获取firstCall的结果,并使用该结果切换到内部可观察对象。

kh212irz

kh212irz2#

你可以使用forkJoin将多个调用加入到一个订阅中。在你的代码中看不到你订阅的函数的名称,所以我只使用name:* 游戏服务.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();
      });

相关问题