(Angular 2/4/5/6) 订阅服务后从服务器获取错误响应

(Angular 2/4/5/6) Get error response from server after subscribing to service

我正在尝试验证我的 otp。根据服务器返回的错误响应(otp 不匹配或 otp 过期),我想相应地显示错误消息。但是,我不确定如何从服务器检索错误响应

目前我的 console.log 正在从我的 otpService 获取一个字符串 "Http failure response for http://xxx/verify: 400 Bad Request",那么我该如何检索 {"Err":"otp expired"} 呢?

otp.component.ts

this.otpService
      .verify(id, this.paymentForm.controls.otp.value)
      .subscribe(
        response => {
          this.router.navigate(["success"]);
        },
        // if otp has error, show error message
        error => {
          console.log(error); //this only gives me 400 Bad Request
        },
      );

otp.service.ts

verify(id: string, token: string): Observable<{}> {
const req = { id: id, otp: otp};
return this.http
  .put<{}>(appConfig.apiBasePath + "verify", req, {
    headers: new HttpHeaders().set(
      "Content-Type",
      "application/json; charset=utf-8",
    ),
  })
  .pipe(
    catchError(this.handleError),
  );

}

感谢您的帮助!

private errorList: string = '';    

public handleError(error) {
        if (error.error) {
          if (error.error instanceof Array) {
            for (var i = 0; i < error.error.length; i++) {
              if (i === 0) {
                this.errorList = error.error[i].description;
              }
              else {
                this.errorList += " " + error.error[i].description;
              }
            }
            return Observable.throw(this.errorList);
          }
          else {
            return Observable.throw(error.error);
          }
        }
        else {
          return Observable.throw(error.message);
        }
      }

只需使用此方法return 您的服务错误