【问题标题】:Apollo Graphql with Angular with headers and Subscriptions带有 Angular 的 Apollo Graphql,带有标题和订阅
【发布时间】:2020-08-17 01:11:06
【问题描述】:

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

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

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

【问题讨论】:

    标签: graphql apollo angular9 graphql-subscriptions


    【解决方案1】:
    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 {}
    

    【讨论】:

      【解决方案2】:

      这是我经过长期努力找到的解决方案! 在你的 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 { }
      

      【讨论】:

        猜你喜欢
        • 2020-10-18
        • 2021-01-08
        • 2019-01-18
        • 2019-01-27
        • 2020-08-31
        • 2020-08-03
        • 2020-02-12
        • 2020-06-20
        • 2017-09-19
        相关资源
        最近更新 更多