我有一个组件,有点像下面的伪代码片段。
我需要修改 onDeployForTesting()
以便它调用 myService.save()
呼叫前 myService.deployForTesting()
. 我一直在研究嵌套的Observables和嵌套的调用,以实现 httpClient
但我永远无法知道哪个Observable失败了(如果有的话)。我需要知道这些,这样我才能继续设置通知。
如何嵌套两个(或多个) httpClient
请求,看看链中哪个请求失败了(以RxJS的方式)?
onSaveAndDeployForTesting() {
this.myService
.save(arg1)
.pipe(
concatMap( // also tried: switchMap, mergeMap
() => this.myService.deployForTesting(arg2),
),
)
.subscribe(
console.info,
console.error, // this gives a very generic error with no pointer to which Observable actually failed
console.info,
);
}
class MyClass {
// other code
onSave() {
this.myService.save(arg1)
.subscribe(
(data) => {
this.notificationService.set({
type: NotificationType.SUCCESS,
title: 'Success',
description: 'Lorem ipsum dolor sit amet',
});
},
(err) => {
if (err.errorCode === 409) {
this.notificationService.set({
type: NotificationType.WARNING,
title: 'Save Conflict',
description: 'Lorem ipsum dolor sit amet',
});
} else {
this.notificationService.set({
type: NotificationType.ERROR,
title: 'Error',
description: 'Lorem ipsum dolor sit amet',
});
}
},
);
}
onDeployForTesting(arg1) {
this.myService.deployForTesting(arg1)
.subscribe(
(data) => {
if (data.status === 207) {
this.notificationService.set({
type: NotificationType.WARNING,
title: 'Unable to deploy configuration',
description: 'Lorem ipsum dolor sit amet',
});
} else {
this.notificationService.set({
type: NotificationType.SUCCESS,
title: 'Success',
description: 'Lorem ipsum dolor sit amet',
});
}
},
(err) => {
this.notificationService.set({
type: NotificationType.ERROR,
title: 'Error',
description: 'Lorem ipsum dolor sit amet',
});
},
);
}
}
class MyService {
// other code
save(data) {
return this.http.put('/my/save/url', data);
}
deployForTesting(data) {
return this.http.post('/my/deploy/url', data);
}
}
你可以使用RxJS catchError
. 请尝试以下方法
import { throwError, of, EMPTY } from 'rxjs';
import { catchError, concatMap } from 'rxjs/operators';
onSaveAndDeployForTesting() {
this.myService.save(arg1).pipe(
catchError(saveError => this.handleSaveError(saveError)),
concatMap(() => this.myService.deployForTesting(arg2).pipe(
catchError(deployError => this.handleDeployError(deployError))
))
)
.subscribe(
console.info,
console.error,
console.info,
);
}
handleSaveError(error) {
// handle error from `save()` call
return EMPTY; // also `throwError()` or `of()`
}
handleDeployError(error) {
// handle error from `deployForTesting()` call
return EMPTY; // also `throwError()` or `of()`
}
记住要从 catchError
.