【发布时间】:2021-09-26 23:15:06
【问题描述】:
我有一个应用程序,它每 10 秒就会随机播放一次笑话。我正在使用 rxjs 中的间隔运算符进行倒计时,10 秒后我发出一个 http 请求以获取一个随机笑话。问题是我使用异步管道在我的模板中显示了两次笑话。我知道这样做会创建两个新订阅并发出两次 http 请求。为了处理这个问题,我尝试使用 shareReplay 或 publish + refCount ,以便只发出一个 http 请求。但它两次调用 getRandomJoke 服务函数。如何解决此问题。
代码和演示 - https://stackblitz.com/edit/angular-ivy-xvtsrw
随机笑话.component.html
<div class="joke-title">{{joke | async}}</div>
<div class="joke-title">{{joke | async}}</div>
<div class="footer">Next Joke in : {{countdown | async}}</div>
随机笑话.component.ts
export class RandomJokesComponent implements OnInit {
joke: Observable<any>;
restartTimer = new Subject();
restartInterval = new Subject();
intervalForJokes: Observable<any>;
countdown: any;
countDownTill = 10;
constructor(private fetchService: FetchUtilService) {}
ngOnInit() {
this.startTimer();
this.getJokesInInterval();
}
getJokesInInterval() {
this.restartInterval.next();
let intervalForJokes = interval(10000);
this.joke = intervalForJokes.pipe(
tap(()=> console.log('getting interval')),
takeUntil(this.restartInterval),
publish(),
refCount(),
switchMap(() =>
this.fetchService.getRandomJoke().pipe(
tap(() => this.startTimer()))
)
);
}
startTimer() {
this.restartTimer.next();
this.countdown = timer(0, 1000).pipe(
takeUntil(this.restartTimer),
map(i => this.countDownTill - i)
);
}
}
获取服务
getRandomJoke(): Observable<any> {
console.log('getting');
return this.http.get(this.apiUrl).pipe(
tap(result => console.log(result)),
// shareReplay(),
publish(),
refCount(),
map((result: any) => result && result.value.joke)
);
}
【问题讨论】: