如今,我有一个发出http请求的功能,当我有响应时,我会执行其他依赖于第一个请求成功结果的http请求。
我有这样的结构:
onSubmit() {
this.service.get().subscribe((res) => {
this.service2.get().subscribe((res) => {
console.log(res);
}, (err) => {
this.toastr.error(err.statusText);
})
}, (err) => {
this.toastr.error(err.statusText);
});
}
我认为这很难理解,我正在尝试以一种更适当的方式使其实现。
有两种方法可以提取此函数,每个函数都有您的错误,并可以与某些Rxjs运算符连接?
答案 0 :(得分:1)
您可以使用任何mergeMap
,concatMap
和switchMap
运算符。究竟是哪一个取决于您的第一个可观察对象将发出多少结果,以及如何处理在第二个可观察对象完成之前第一个可观察对象再次发出的情况。
onSubmit() {
this.service.get()
.pipe(
.switchMap(result1 => {
// this will be called once the first call finished, with it's result
// here you can use the first result
console.log(`result of the service1 call: ${result1}`);
// you could even pass it to the 2nd one if it needed it
// here you have to return an observable
return this.service2.get();
}),
.catchError(err => {
// you can omit this `catchError`
// here you can handle errors, but this will receive errors from either of the service calls
// and you have to return an observable from here too
})
).subscribe(result2 => console.log(`result of service2 call: ${result2}`))
}