首页 > 解决方案 > 如何延迟 Angular 7 中错误的 http 响应

问题描述

我正在开发一个 Angular7 项目,并且对 http 请求的错误处理有一些问题。

这是我的登录组件,有两个功能

export class LoginComponent implements OnInit, OnDestroy {

    emailLogin1() {

        this.authService.emailLogin1(this.loginForm.value).pipe(delay(1000)).subscribe(
            (response) => {
                console.log(response);
            },
            (error) => {
                console.log(error);
            }
        );

    }

    emailLogin2() {

        this.authService.emailLogin2(this.loginForm.value).pipe(delay(1000)).subscribe(
            (response) => {
                console.log(response);
            },
            (error) => {
                console.log(error);
            }
        );

    }

}

这是我的 AuthService 有两个功能。

export class AuthService {

    constructor(private http: HttpClient) {
    }

    emailLogin1(values): any {

        return this.http.post(environment.server + '/auth/emailLogin', values).pipe(
            tap(
                (response) => {
                    localStorage.setItem('token', response['token']);
                },
                (error) => {
                    console.log(error);
                }
            )
        );

    }

    emailLogin2(values): any {

        return this.http.post(environment.server + '/auth/emailLogin', values).pipe(
            tap(
                (response) => {
                    localStorage.setItem('token', response['token']);
                }
            ),
            catchError((error) => {
                console.log(error);
                throw error;
            })
        );

    }

}

当我向服务器发出请求时,如果响应状态成功,它会等待 1000 毫秒,然后按预期显示结果。但如果响应返回错误,则延迟(1000)函数不工作并且错误块立即工作。我尝试了有无catchError。两者的工作方式完全相同。

标签: angular7rxjs6

解决方案


操作员将仅处理通过“下一个”通知通过可观察对象发送的delay事件(在您的情况下,这是“成功”)。发生错误时,它会作为“错误”通知发送,并直接跳过您的delay操作员。如果你想延迟错误,你应该捕获它,引入延迟,然后重新抛出它:

emailLogin1() {
  this.authService.emailLogin1(this.loginForm.value).pipe(
    delay(1000), // only affects "success"
    catchError(error => interval(1000).pipe( // only affects "error"
      mergeMap(() => throwError(error)) // re-throw error after our delay
    )),
  ).subscribe(
    (response) => {
      console.log(response);
    },
    (error) => {
      console.log(error);
    }
  )
}

推荐阅读