如何正确处理httpClient?
How to properly handled httpClient?
这是我当前的代码,
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)
},
);
}
控制台显示错误
Handling error locally and rethrowing it... Unknown Error
app.component.ts:190 error Unknown Error
zone-evergreen.js:2845 GET http://172.16.0.115:8080/connection net::ERR_INTERNET_DISCONNECTED
我要获取错误测试
"ERR_INTERNET_DISCONNECTED"
我们可以手动处理。
你应该添加给我们用户状态的方法
然后在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)
})
}
我相信您可以简单地从错误字符串中提取错误,下面是如何使用正则表达式完成此操作的示例
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)
这是我当前的代码,
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)
},
);
}
控制台显示错误
Handling error locally and rethrowing it... Unknown Error
app.component.ts:190 error Unknown Error
zone-evergreen.js:2845 GET http://172.16.0.115:8080/connection net::ERR_INTERNET_DISCONNECTED
我要获取错误测试 "ERR_INTERNET_DISCONNECTED"
我们可以手动处理。
你应该添加给我们用户状态的方法
然后在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)
})
}
我相信您可以简单地从错误字符串中提取错误,下面是如何使用正则表达式完成此操作的示例
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)