问题:我目前使用可观察对象从我的 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/