Apollo Graphql 与 Angular 且未传递标头

问题描述 投票:0回答:1

我需要使用 Angular 将标头添加到我的 graphql 请求中,但我没有找到任何方法。当我使用查询但不变异时添加标头。另外,如果我不添加标头,mutate 也会起作用。这是我的代码:

import { APP_INITIALIZER, NgModule } from '@angular/core';
import { AppComponent } from './app.component';

import { Amplify } from 'aws-amplify';
import {AppsyncService} from './appsync.service';
import { MatDialogModule, MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';

import { TranslateLoader, TranslateModule } from '@ngx-translate/core';
import { TranslateHttpLoader } from '@ngx-translate/http-loader';
import { HttpClient, HttpClientModule } from '@angular/common/http';
import { AuthGuard } from './services/authcheck.guard';
import {MatSidenavModule} from '@angular/material/sidenav';
import { NgxSkeletonLoaderModule } from 'ngx-skeleton-loader';
import { HttpLink, HttpLinkModule } from 'apollo-angular-link-http';
import { HttpHeaders } from '@angular/common/http';
import { InMemoryCache } from '@apollo/client/core';
import { Apollo, APOLLO_OPTIONS, ApolloModule } from 'apollo-angular';

export function HttpLoaderFactory(http: HttpClient) {
  return new TranslateHttpLoader(http, './assets/i18n/', '.json');
}

let awsConfig ;
Amplify.configure(awsConfig);

const uri = 'https://www.xxxxxxx..appsync-api.ap-southeast-1.amazonaws.com/graphql';

export function createApollo(httpLink: HttpLink): any {
  const http = httpLink.create({ uri });
  console.log(http);
  // Add headers to the HTTP link
  const authHeader = new HttpHeaders().set('Host', 'abc.com'); 
  const link = httpLink.create({ uri, headers: authHeader });

  console.log(link);
  return {
    link,
    cache: new InMemoryCache(),
  };
}

@NgModule({
  declarations: [
    AppComponent,
  ],
  imports: [
    MatSidenavModule,
    NgxSkeletonLoaderModule,
    TranslateModule.forRoot({
      defaultLanguage: 'en',
      loader: {
          provide: TranslateLoader,
          useFactory: HttpLoaderFactory,
          deps: [HttpClient]
      }
    })
  ],
  exports: [
    TranslateModule,
    HttpClientModule, ApolloModule, HttpLinkModule
  ],
  providers: [
    AuthGuard,
    AppsyncService,
    {
      provide: APOLLO_OPTIONS,
      useFactory: createApollo,
      deps: [HttpLink],
    },
    {
      provide: MatDialogRef,
      useValue: {}
    },
    { provide: MAT_DIALOG_DATA, useValue: {} },
  ],
  bootstrap: [AppComponent]

})
export class AppModule { }

它没有将标头传递给我的 graphql 请求。我是否遗漏或做错了什么?

angular graphql apollo
1个回答
0
投票

尝试这样,

      const basic = setContext((op, ctx) => ({
        headers: new HttpHeaders().set('Host', 'abc.com')
      }));
     
      const link = ApolloLink.from([basic, httpLink.create({ uri })]);
     
      return {
        link,
        cache: new InMemoryCache()
      };
© www.soinside.com 2019 - 2024. All rights reserved.