Apollo Graphql with Angular with headers and Subscriptions

Apollo Graphql with Angular with headers and Subscriptions

我需要将 headers 添加到我的带有 angular 订阅的 graphql 请求。但我没有找到任何办法。如果我只使用 headers 而没有订阅,将添加 headers。此外,如果我不添加 headers,订阅将有效。但是,两者都行不通。这是我的代码

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 { }

这里headers就不加了。任何解决方案?

import { NgModule } from "@angular/core";
import { HttpClientModule, HttpHeaders } 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 } from "apollo-link";
import { setContext } from "apollo-link-context";
import { WebSocketLink } from "apollo-link-ws";
import { getMainDefinition } from "apollo-utilities";
import ApolloClient from "apollo-client";

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

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

const authMiddleware = new ApolloLink((operation: any, forward: any) => {
  operation.setContext({
    headers: new HttpHeaders().set(
      "Authorization",
      `Bearer ${localStorage.getItem("token")}` || null,
    ),
  });

  return forward(operation);
});

export function createApollo(httpLink: HttpLink) {
  return {
    link: from([
      authMiddleware,
      split(
        ({ query }) => {
          const { kind, operation } = getMainDefinition(query);
          return kind === "OperationDefinition" && operation === "subscription";
        },
        subscriptionLink,
        httpLink.create({
          uri: "http://localhost:5000/graphql",
        }),
      ),
    ]),
    cache: new InMemoryCache(),
  };
}

@NgModule({
  exports: [HttpClientModule, ApolloModule, HttpLinkModule],
  providers: [
    {
      provide: APOLLO_OPTIONS,
      useFactory: createApollo,
      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 { }