angular - RXJS 在新值可用时取消订阅

标签 angular typescript rxjs observable

问题:我目前使用可观察对象从我的 API 请求游戏数据。 每次用户从一个游戏切换到另一个游戏时,它都会请求此数据,但如果用户的互联网连接速度太慢而无法跟上游戏的快速变化,它会显示之前请求的数据。

this.gamesService.selectedGame.subscribe((selectedGame) => {
  // Reset current value
  this.setRounds(null);

  // Fetch new game values
  if (selectedGame) {
    this.apiService.get(`Games/${selectedGame.IntGameID}`)
      .subscribe(
        data => this.setRounds(data)
      );
  }
});

gamesService.selectedGame 每次用户切换到不同的游戏时输出一个值。我正在寻找一种方法来取消之前的“订阅”,并且只针对最新的请求运行这段代码。

最佳答案

正如 JB nizet 指出的那样,我确实需要使用 switchMap 运算符。这导致了以下代码。

this.gamesService.selectedGame.pipe(switchMap(
  (selectedGame) => {
    // Reset current value
    this.setRounds(null);

    // Fetch new game values
    return this.apiService.get(`Games/${selectedGame.IntGameID}`);
  })).subscribe(
    data => this.setRounds(data)
  );

关于angular - RXJS 在新值可用时取消订阅,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58048990/

相关文章:

css - 在 Angular2 中创建具有固定页眉和页脚的登录页面

angular - 从 FormGroup 中的输入 FormControl 订阅 valueChanges

java - 如何在 Java EE Spring Boot Web 应用程序中使用 Angular 2 减少构建时间

angular - redux-observable 不会在 catchError 之后执行

angular - 使用 Jest 和 Spectator 测试 Angular 拦截器的响应

node.js - 在 NestJS 中创建代理

typescript - 检测 TypeScript 中的循环依赖

javascript - 如何防止 Element.focus() 在 contenteditable div 中更改光标位置?

javascript - 使用 RxJS 创建一个切换按钮

javascript - 带反压的 Rxjs 缓冲区实现