angular - RxJS 延迟 switchMap 新的 observable 执行
问题描述
在我的 Angular 项目中,我正在进行一些 HttpClient 调用,响应后我需要检查它的主体并执行另一个 HttpClient 调用,具体取决于第一个响应。另外我需要延迟一些时间来执行第二个 HttpClient 调用。
我可以使用switchMap
运算符来做到这一点,但我想知道如何以正确的方式延迟第二次 http 调用。
这是一个非常简单的例子:
export class AppComponent {
ngOnInit() {
this.execute().subscribe(r => console.log(r))
}
execute(): Observable<string> {
return this.http1Call().pipe(switchMap((r) => {
// Checking if 2d http call must be executed or not
if (r === '1st call') {
console.log('---Invalid 1st call, executing 2d')
// TODO: Is that correct way to execute http2Call with delay ???
return of({}).pipe(delay(3000), switchMap(() => this.http2Call()))
}
return of(r);
}));
}
http1Call(): Observable<string> {
return of('1st call').pipe(delay(1000));
}
http2Call(): Observable<string> {
console.log('------Inside http2Call')
return of('--------2d call response').pipe(delay(3000));
}
}
解决方案
你所拥有的基本上没问题,你可以简化(或者更明显)你延迟的部分:
return timer(3000).pipe(switchMapTo(this.http2Call()))
timer()
一个参数只会在延迟后发出一次。你也可以使用concatMap/concatMapTo
代替,switchMap/switchMapTo
因为在这种情况下你永远不会切换任何东西(timer
只发出一次然后完成)。
推荐阅读
- python - 寻找发射火箭的最佳建筑物的最有效方法是什么?
- c - 为 dkms 禁用 -Werror
- javascript - Vue.js 在 v-for 循环中访问嵌套对象
- html - 如何使左 div 的内容 bang 右 div?
- python - Scrapy - 如何使用 python 在网络链接中抓取网络链接?
- google-cloud-platform - 是否可以为同一项目中的不同用户设置不同的 BigQuery 配额?
- javascript - 如何使用从右向左滚动并在没有滞后的情况下重新开始的 css 文本创建过渡
- xml - 如何在 InstallScript 中读取 XML 节点的值
- python - Gitpython 初始化并推送一个新的 repo
- database - 我的 GridDB 节点不想加入同一个集群