【问题标题】:Subscribe executed while getting error in angular 6在 Angular 6 中出现错误时执行订阅
【发布时间】:2018-07-11 22:07:26
【问题描述】:

最近我将 angular 5 升级到了 angular 6,因此我将服务代码升级如下:

register(postBody: any): Observable<any> {
return this.http
  .post(this.remoteUrl + "auth/register", postBody)
  .pipe(
    catchError(this.handleError("register", []))
  );
}

this.authService.register(this.formObj.value).subscribe(
    response => {

    }
)

现在当我从 API 收到 400 错误时。我能够在错误处理程序中捕获此错误,但仍执行订阅,为什么?只有在没有错误的响应时才应该调用订阅。

我对此并不陌生,但在 Angular 5 中并没有发生。那么谁能纠正我做错了什么?

【问题讨论】:

  • handleError 是做什么的?如果它返回一个 of 而不是 throw observable,则会吞下错误。
  • 谢谢伙计。你是对的。

标签: angular6 rxjs6


【解决方案1】:

订阅可让您处理从您的注册函数返回的任何内容。但是为什么你只是捕捉错误,你至少应该映射你的结果并在成功时返回它。另外我不认为你应该做什么来捕捉和抛出错误。

希望对你有帮助

register(postBody: any): Observable<any> {
return this.http
  .post(this.remoteUrl + "auth/register", postBody)
  .pipe(
    map(data => data), //this will return the response when success
    catchError(this.handleError(err =>{
        //Here you can do something like
         err.code === 404 
         ? throwError("Not found")
         : throwError(err)
    }) 
  );
}

this.authService.register(this.formObj.value).subscribe(
    response => {
      // Do stuff whith your result
    },
    err => {
      // Do stuff whith your error
    },
    () => {
      // Do stuff after completion
    },
)

【讨论】:

  • 这是正确答案。为什么它没有被标记为正确?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多