angular - 如何捕获 angular(ionic) 中的 http 错误?

标签 angular ionic-framework rxjs

我试图在 ionic4 应用程序中使用以下代码捕获错误代码为 400 的 HTTP 错误。但是它没有捕捉到它,这里出了什么问题。控制台日志行均未执行,但在 firefox 控制台中显示 400 错误。

export class AuthService {

  constructor(private httpClient: HttpClient)  {}

  login(email: string, password: string){

    const data = {
      password: password,
      email: email,
    }

    this.httpClient.post(url, data).pipe(
      tap((res: IAuthResponse) => {
        console.log("Catch error 1") 
        return res;
      }),
      catchError((error) => {
        console.log("Catch error 2")
        return Observable.throw(new Error(error.status));
      })
    ).subscribe( 
       (result) => {
         console.log("Catch error 3")
       },
       (error) => {
          console.log("Catch error 4")
       }
    );
  }

enter image description here

实际上我只是想在我编码 console.log 行的任何地方处理这个错误。找到了很多这样的例子,但没有一个有效。

编辑:在我的真实代码中,控制台日志第 1 行在 AuthService 类中,但订阅代码在不同的类文件中。这两个类都必须根据结果进行一些初始化。所以我需要同时拥有管道代码和订阅代码。

最佳答案

这是可以做到的方式

Here is working Example

this.httpClient.post("ssdsdsd", data).pipe(
      (res: any) => {
        console.log("Catch res ") 
        return res;
      },
    ).subscribe( 
       (result) => {
         console.log("Catch result ")
       },
       (error) => {
          console.log("Catch error ")
       }
    );

关于angular - 如何捕获 angular(ionic) 中的 http 错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57106701/

相关文章:

angular - "No component factory found for"尝试从一页推送到另一页时出错

ANGULAR:无法让我的数据显示在我的 HTML 文件上

Angular2访问数组Observable中的第一个元素

angular 2 - 如何使用模板引用变量获取子组件的 HTMLElement/ElementRef?

android - getUserMedia 在 Android 应用程序的 ionic-webview 中工作吗?

unity3d - 我如何集成 Unity APP 和 Ionic

mobile-website - 移动浏览器上的 ionic 侧边菜单无法正常工作

Angular2 - Rxjs 主题即使在取消订阅后也会运行两次

angular - 想要循环订阅API调用

html - 如何检测 Angular 中元素外部的点击?