使用角度中的apollo捕获http状态代码

问题描述 投票:2回答:2

我是角色的新手。我正在使用Apollo客户端来执行graphql查询。我需要检查我得到的状态代码并返回消息。请帮我做同样的事。这是我使用的代码。如何捕获我得到的状态代码。附件将显示我如何获取状态代码.enter image description here

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);
      }
    );
angular angular7 apollo apollo-client
2个回答
3
投票

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

0
投票

Apollo提供了一种通过链接处理错误的综合方法,特别是apollo-error-link。与使用HttpInterceptor不同,这允许您指定网络错误的逻辑以及响应中包含的错误,作为errors数组的一部分:

import { onError } from 'apollo-link-error';

const link = onError(({ graphQLErrors, networkError }) => {
  if (graphQLErrors)
    graphQLErrors.map(({ message, locations, path }) =>
      console.log(
        `[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`,
      ),
    );

  if (networkError){
    console.log(`[Network error]: Status: ${networkError.statusCode}`);
  }
});

此链接还可以与apollo-link-retry结合使用,以实现更平滑的错误处理。链接组成然后传递给客户端的构造函数,例如:

const errorLink = onError(...);
const httpLink = new HttpLink(...);
const link = ApolloLink.from([
  errorLink,
  httpLink,
]);

const client = new ApolloClient({
  link,
  ...
})
© www.soinside.com 2019 - 2024. All rights reserved.