Angular 拦截Apollo/graphql请求

Angular 拦截Apollo/graphql请求,angular,error-handling,apollo,apollo-client,express-graphql,Angular,Error Handling,Apollo,Apollo Client,Express Graphql,我们在应用程序中使用Apollo/Graphql,我们面临一个问题 该应用程序是在Angular 5中开发的,NodeJS作为后端,graphql服务器将响应前端。 为了在angular中拦截Http请求,我们实现了“HttpInterceptor”,这样我们就可以用定制的方式处理错误。但是,阿波罗的请求不会通过这个拦截器 为了正确处理错误,我们使用“阿波罗链接错误” 但我们想知道是否有可能以类似于HttpInterceptor的方式拦截阿波罗的请求。嗨,我也遇到了同样的问题 红色标志: Apo

我们在应用程序中使用Apollo/Graphql,我们面临一个问题

该应用程序是在Angular 5中开发的,NodeJS作为后端,graphql服务器将响应前端。 为了在angular中拦截Http请求,我们实现了“HttpInterceptor”,这样我们就可以用定制的方式处理错误。但是,阿波罗的请求不会通过这个拦截器

为了正确处理错误,我们使用“阿波罗链接错误”


但我们想知道是否有可能以类似于HttpInterceptor的方式拦截阿波罗的请求。

嗨,我也遇到了同样的问题

红色标志:

Apollo链接使您可以创建中间件来修改请求 在它们被发送到服务器之前

以下是一个例子:

import { HttpHeaders } from '@angular/common/http';
import { Apollo } from 'apollo-angular';
import { HttpLink } from 'apollo-angular-link-http';
import { setContext } from 'apollo-link-context';
import { InMemoryCache } from 'apollo-cache-inmemory';

@NgModule({ ... })
class AppModule {
  constructor(
    apollo: Apollo,
    httpLink, HttpLink
  ) {
    const http = httpLink.create({uri: '/graphql'});

    const auth = setContext((_, { headers }) => {
      // get the authentication token from local storage if it exists
      const token = localStorage.getItem('token');
      // return the headers to the context so httpLink can read them
      // in this example we assume headers property exists
      // and it is an instance of HttpHeaders
      if (!token) {
        return {};
      } else {
        return {
          headers: headers.append('Authorization', `Bearer ${token}`)
        };
      }
    });

    apollo.create({
      link: auth.concat(http),
      // other options like cache
    });
  }
}

我认为拦截Apollo客户端请求的官方方式是通过Apollo链接

但是,如果您使用Angular,也可以通过HttpInterceptor来实现。您可以在使用Apollo客户端时查看我发表的这篇文章


希望这能有所帮助。

感谢您的回答和时间。是的,我完全同意,在提出请求之前,我们使用它来设置标题。但我们正在寻找一种与HttpInterceptor一样处理错误的方法;您好,“与HttpInterceptor相同的方式”是什么意思?您可以使用售后服务:“售后服务”与中间件非常相似,只是在发出请求后运行售后服务,也就是说响应将得到处理。您在博客中提到“apollo angular link http在后台使用HttpClient”,我想知道是阿波罗链接使用Angular HttpClient,还是技术上阿波罗Angular Client在引擎盖下也使用HttpClient?