graphql - Apollo Graphql 与 Angular 以及标题和订阅

标签 graphql apollo angular9 graphql-subscriptions

我需要使用带有订阅的 Angular 向我的 graphql 请求添加 header 。但我没有找到任何办法。如果我只使用没有订阅的标题,则会添加标题。另外,如果我不添加标题,订阅也将起作用。但两者兼而有之,则行不通。这是我的代码

import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';
import { ApolloModule, Apollo, APOLLO_OPTIONS } from 'apollo-angular';
import { HttpLinkModule, HttpLink } from 'apollo-angular-link-http';
import { InMemoryCache } from 'apollo-cache-inmemory';
import { ApolloLink, split } from 'apollo-link';
import { setContext } from 'apollo-link-context';
import { WebSocketLink } from 'apollo-link-ws';
import { getMainDefinition } from 'apollo-utilities';

const uri = 'http://localhost:5000/graphql';

export function provideApollo(httpLink: HttpLink) {
  const basic = setContext((operation, context) => ({
    headers: {
      Accept: 'charset=utf-8'
    }
  }));

  // Get the authentication token from local storage if it exists
  const token = localStorage.getItem('token');
  const auth = setContext((operation, context) => ({
    headers: {
      Authorization: `Bearer ${token}`
    },
  }));

  const subscriptionLink = new WebSocketLink({
    uri:
      'ws://localhost:5000/graphql',
    options: {
      reconnect: true,
      connectionParams: {
        authToken: localStorage.getItem('token') || null
      }
    }
  });

  const link = split(({ query }) => {
    const { kind } = getMainDefinition(query);
    return kind === 'OperationDefinition';
  }, subscriptionLink, ApolloLink.from([basic, auth, httpLink.create({ uri })]));



  // const link = ApolloLink.from([basic, auth, httpLink.create({ uri }), subscriptionLink]);
  const cache = new InMemoryCache();
  return {
    link,
    cache
  };
}

@NgModule({
  exports: [
    HttpClientModule,
    ApolloModule,
    HttpLinkModule
  ],
  providers: [{
    provide: APOLLO_OPTIONS,
    useFactory: provideApollo,
    deps: [HttpLink]
  }]
})
export class GraphQLModule { }

这里不会添加标题。有什么解决办法吗?

最佳答案

这是我找到的解决方案。 将以下代码导入到您的 app.module.ts

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { HttpHeaders } from '@angular/common/http';

import { APOLLO_OPTIONS } from "apollo-angular";
import { WebSocketLink } from 'apollo-link-ws';
import { getMainDefinition } from 'apollo-utilities';
import { split } from 'apollo-link';
import { InMemoryCache } from "apollo-cache-inmemory";
import { HttpLink } from 'apollo-angular-link-http';

@NgModule({
  imports: [
    CommonModule,
  ],
  providers: [
    {
      provide: APOLLO_OPTIONS,
      useFactory(httpLink: HttpLink) {

        const http = httpLink.create({
          uri: 'http://localhost/v1/graphql',
          headers: new HttpHeaders({
            "x-hasura-admin-secret": "mysecretkey"
          })
        })

        const ws = new WebSocketLink({
          uri: `ws://localhost/v1/graphql`,
          options: {
            reconnect: true,
            connectionParams: {
              headers: {
                "x-hasura-admin-secret": "mysecretkey"
              }
            }
          }
        });

        const link = split(
          // split based on operation type
          ({ query }) => {
            const definition = getMainDefinition(query);
            return (
              definition.kind === 'OperationDefinition' &&
              definition.operation === 'subscription'
            );
          },
          ws,
          http,
        );

        return {
          link,
          cache: new InMemoryCache(),
        };
      },
      deps: [HttpLink],
    },
  ]
})
export class GraphqlModule { }

关于graphql - Apollo Graphql 与 Angular 以及标题和订阅,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61561227/

相关文章:

javascript - 后端扩展时如何有效地向graphql订阅者发布

javascript - 如何在 Apollo GraphQL 解析器上的一个函数中解析 2 个不同的方法?

javascript - NextJS SSR 可以与 Apollo 客户端一起使用吗?在第一次加载页面上检查 'view page source' 时,我看不到我的 HTML

angular - 基于 angular 9 迁移的 angular 生产问题

javascript - Zone.js 检测到 ZoneAwarePromise `(window|global).Promise` 已被覆盖。正确使用polyfills

reactjs - Apollo 客户端缓存与 Redux

amazon-web-services - 如何将默认GraphQL参数传递给AWS AppSync解析器

javascript - 删除突变返回 null

javascript - Apollo 客户端本地状态缓存竞争条件?

angular - 将 Angular 6 升级到 9 的最佳方法是什么?