angular - 使用 apollo 在 Angular 中捕获 http 状态代码
问题描述
我是角度新手。我正在使用 Apollo 客户端执行 graphql 查询。我需要检查我得到的状态码并返回消息。请帮我做同样的事情。这是我使用的代码。如何捕获我获得的状态代码。附件将显示我如何获得状态代码。
let res = this.apollo.use('dataManipulation').query({
query: myquery,
fetchPolicy: 'network-only',
variables:{
userId: this.userId
}
});
res.subscribe(listData => {
this.studyData=[];
this.resourceData=listData.data['StudyList'];
this.resourceData.entry.forEach(data =>{
const customFormat= {
id:data.resource.id,
title:data.resource.title,
}
this.studyData.push(customFormat);
console.log("studyData",this.studyData)
});
},
err => {
console.log("----------",err);
}
);
解决方案
如果是针对每条消息,我建议您使用HTTP Interceptor。
@Injectable()
export class YouInterceptor implements HttpInterceptor {
constructor() { }
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(request).pipe(
catchError(error => this.handleError(error))
);
}
private handleError(error: HttpErrorResponse): Observable<any> {
if (error.status === 404) {
// Do your thing here }
return EMPTY;
}
}
并导入它:
@NgModule({
bootstrap: [AppComponent],
imports: [...],
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: YouInterceptor,
multi: true
}
]
})
export class AppModule {}
推荐阅读
- wordpress - 谷歌站点地图插件生成不正确的 URL
- php - 在 php、mysql 中以“内联编辑”样式编辑回显输出-
- jquery - HTML 访问密钥 (alt+s) 在 CK 编辑器中不起作用
- powershell - 如何使用 powershell 中的命令将 sudo 用户添加到 WSL?
- fusionauth - 是否可以在用户注册期间强制执行 2FA 配置?
- ruby - Rails:Active Storage 变体生成一个附加文件
- angular - JSON值降序排序的问题
- sql - 如何编写只选择一些字母的sql?
- php - 如何在 php-fpm 后面的 docker 中获取 laravel 的日志?
- c# - 同步 dbcontext 查询列表重写为单独上下文上的异步调用