angular - 如果 Api 离线,则 Angular 状态为 0
问题描述
如果 API 在我的 Angular 应用程序上脱机,我正在尝试显示一条消息。
在我的 HttpInterceptor 中,我有:
return next.handle(request).pipe(
tap(
event => {
if (event instanceof HttpResponse) {
// console.log('all looks good');
// http response status code
//console.log(event.status);
}
},
error => {
if (error.status == 0) {
error.message = 'API is Offline.', 'error'
}
console.error(error.status);
console.error(error.message);
}
)
);
因此,当他失败时,我想拦截错误以返回我的组件或服务的消息。
我的组件调用服务:
this._service.new()
.subscribe(
res => {
},
err => {
this._messageHelperService.showToast(err.error.message, 'error');
}
);
有人可以帮助我吗?谢谢。
解决方案
尝试throwError
在 HttpInterceptor 中使用抛出错误。
例子:
tap(
event => {
if (event instanceof HttpResponse) {
// console.log('all looks good');
// http response status code
//console.log(event.status);
}
},
error => {
if (error.status === 0) {
return throwError('API is Offline., error')
// error.message = 'API is Offline.', 'error'
}
console.error(error.status);
console.error(error.message);
}
)
);
然后您可以以与您使用相同的方式访问组件中的错误。
推荐阅读
- php - 使用 json_encode() 时如何添加空格和换行符?
- apache-kafka - kafka-connect:在连接器接收器 cassandra 的分布式配置中出现错误
- vue.js - Nuxt 添加参数无需页面且无需重新加载页面
- javascript - 功能无法识别
- angularjs - 在生成 AngularJS 项目的构建时获取 Uglifying source .tmp/concat/scripts/scripts.js 失败
- python - 在 Windows 10 上使用 django 连接到远程 mysql
- c# - 将所有非字母字符从一个字符串移动到 char 数组
- c++ - 如何结束图形 GUI 并执行控制台功能(QT)?
- python-3.x - 在 Pyaudio 中检测哨子
- r - 为什么“write.dat”(R)将数据文件保存在文件夹中?