向订阅RXJS发送错误

时间:2018-08-30 09:38:47

标签: error-handling rxjs

我创建了一个应该捕获错误的函数:

private pipeError(): any {
 return catchError((error: HttpErrorResponse, caught: Observable<any>): 
                    HttpErrorResponse | any => {
 if (error.status === 400 || error.status === 402) {
    return Observable.throw(error);  
 } else if (error.status === 401) {
    this.router.navigate(['/login']);
    return Observable.throw(error);
   }
 });
}

然后我创建了一个函数,该函数应该向api发送查询:

private post(path: string, data: Object, headers: HttpHeaders = this.getHeaders()): Observable<Object> {
    return this.http.post(`${this.apiUrl}${path}`, data, { headers }).pipe(
      this.pipeError(),
      map((response: Object): Object | any => {
        if (response instanceof Object) {
          return response;
        } else {
          return empty();
        }
      })
    );
  }

为了调用上面的函数,我创建了一个新函数,在其中传递了适当的参数:

userRegister(data: UserRegisterInterface): Observable<Object> {
    return this.post('accounts/register/', data);
  }

其他组件: 现在,在另一个组件中,您可以订阅此功能

this.createAccountSubscription = this.api.userRegister(datadata).subscribe((data) => {
      console.log(data);
    }, error => {
      console.log(error);
    });

我希望我的pipeError函数返回到此错误订阅,但这不起作用,它可以做到:

enter image description here

1 个答案:

答案 0 :(得分:0)

您并不总是处理该错误。我认为您可以像这样重写pipeError()

import { throwError } from 'rxjs';

private pipeError(): any {
    return catchError((error: HttpErrorResponse, caught: Observable<any>):
        HttpErrorResponse | any => {
        if (error.status === 401) {
            this.router.navigate(['/login']);
        }

        return throwError(error);
    });
}