【问题标题】:How to properly handled httpClient?如何正确处理httpClient?
【发布时间】:2021-01-15 07:58:35
【问题描述】:

这是我当前的代码,

service.ts

export class ApiServiceFunction {
    constructor(
        private http: HttpClient
    ) { }

    // in app.ts for test connection
    testConnection() {
        return this.http.get(`${environment.apiUrl}/connection`)
        .pipe(
            catchError(err => {
                console.log('Handling error locally and rethrowing it...', err);
                return throwError(err);
            })
        );
    }
}

component.ts

  private testConnection() {
    this.ApiServiceFunction.testConnection()
    .subscribe(
      data => {
        console.log('data ', data)
      },
      error => {
        console.log('error ',error)

      },
    );
  }

控制台显示错误

在本地处理错误并重新抛出它...未知错误

app.component.ts:190 错误未知错误

zone-evergreen.js:2845 GET http://172.16.0.115:8080/connection net::ERR_INTERNET_DISCONNECTED

我想得到错误测试 “ERR_INTERNET_DISCONNECTED”

【问题讨论】:

  • 查看本教程:joshmorony.com/…
  • @NajamUsSaqib 感谢您的分享。我看了一下这个例子,但它没有解决我的问题。问题是,出现错误时我无法得到确切的错误。

标签: angular typescript ionic-framework httpclient


【解决方案1】:

我们可以手动处理。

您应该添加为我们提供用户状态的方法

然后在catchError 块句柄行为

    get isOnline() {
        return navigator.onLine;
    }

    testConnection() {
        return this.http.get(`${environment.apiUrl}/connection`)
            .pipe(catchError(e => {
                if (!this.isOnline) {
                    return throwError('ERR_INTERNET_DISCONNECTED')
                }
                return throwError(e)
            })
    }

【讨论】:

  • 这是一个很好的使用 navigator.online 的提示。但是,如何检查 -net::ERR_NETWORK_CHANGED -net::ERR_CONNECTION_TIMED_OUT
  • 这是另一个问题
  • @saifuladham 在您的情况下,我们可以实现将跟踪更改的 OfflineInterceptor。见链接netbasal.com/…
【解决方案2】:

我相信您可以简单地从错误字符串中提取错误,下面是如何使用正则表达式完成此操作的示例

const err = "zone-evergreen.js:2845 GET http://172.16.0.115:8080/connection net::ERR_INTERNET_DISCONNECTED unknown err";

const extractErr = err.match(/net\:\:([A-Z|_]+)/gm)[0].split('::')[1]

console.log(extractErr)

【讨论】:

    猜你喜欢
    • 2013-10-02
    • 2019-02-01
    • 1970-01-01
    • 2016-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多