首页 > 解决方案 > 使用 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);
      }
    );

标签: angularangular7apolloapollo-client

解决方案


如果是针对每条消息,我建议您使用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 {}

推荐阅读