1

我试图用它concatMap来允许我按顺序运行请求,而不必在视觉上订阅我发送的每个请求。

一切正常,但是当出现错误时,它会继续通过管道运行,这是我不想要的。

如果它失败了,我只想能够取消所有的请求,让它停止运行并显示一些东西。我已经尝试过catchError,但这似乎不起作用/做我想做的事。

举这个例子...

我想重置用户密码,在密码重置后我想登录POST/password/resets端点,然后我想自动登录用户,所以我想发帖,/auth/login然后我想获取用户GET - /user以便我可以使用它在整个应用程序中。如果请求在任何阶段失败。我想停止管道并抛出问题底部显示的一般错误。

this.userService.resetPassword(password)
.pipe(concatMap(() => this.authService.login(user.email, password)))
.pipe(concatMap(() => this.userService.me()))
.subscribe((user: User) => {
    this.userService.setUser(user);
});

例子:

this.userService.resetPassword(password)
.pipe(concatMap(() => this.authService.login(user.email, password)))
<-- IF IT FAILS ON THE ABOVE / ANY REQUEST I WANT TO STOP ALL REQUESTS AND SHOW NOTIFICATION -->
.pipe(concatMap(() => this.userService.me()))
.subscribe((user: User) => {
    this.userService.setUser(user);
});

下面的代码片段是我想在错误时运行的东西 -

this.notificationService.notify('Unable to reset password, please try again.');
4

3 回答 3

0

你可以将catchError添加到同一级别的concatMap吗?(喜欢:)

// also no need to put pipe for each piping. You can add a single one
this.userService.resetPassword(password)
  .pipe(concatMap(() => this.authService.login(user.email, password)),
        concatMap(() => this.userService.me()),
        catchError(err => throwError('error'))
  .subscribe((user: User) => {
    this.userService.setUser(user);
});

这个 catch 错误应该在途中捕获任何错误,并将其扔回。如果我没错的话。如果您在 concatMap 中捕获它,您正在解析该 innerObservable,但外部仍在继续。因此,您需要停止更高层以使其按您的意愿运行。

于 2019-06-25T14:17:48.140 回答
0

The way you use pipe and the rxjs operators are making it impossible to catch. The catchError operator can catch the exceptions throughout the pipe it is in.

Could you correct it and try once more?

yourCall().pipe(
    concatMap(() => otherCall()),
    concatMap(() => otherCall()),
    catchError( error => handleError())
).subscribe(result => doWhatYouWant());
于 2019-06-25T14:23:37.023 回答
-1

您可以使用 catchError https://blog.angular-university.io/rxjs-error-handling/ 此外,您可以在单个 pipe() 中链接调用而不是重复它。

类似的东西

this.userService.resetPassword(password)
.pipe(
    concatMap(() => this.authService.login(user.email, password).pipe(
        map(() => this.userService.me()),
        catchError(error => doSomething)))),
    ).subscribe((user: User) => {
    this.userService.setUser(user);
});
于 2019-06-25T13:41:39.083 回答