Created
August 8, 2019 13:13
-
-
Save waiholiu/e5294b11684569bbfb156fea63424e1a to your computer and use it in GitHub Desktop.
How to insert custom headers (eg. auth token) into an apollo request in Angular module
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { LocalStorageService } from 'angular-2-local-storage'; | |
import { NgModule } from '@angular/core'; | |
import { ApolloModule, APOLLO_OPTIONS, Apollo } from 'apollo-angular'; | |
import { HttpLinkModule, HttpLink } from 'apollo-angular-link-http'; | |
import { InMemoryCache } from 'apollo-cache-inmemory'; | |
import { ApolloLink } from 'apollo-link'; | |
// const uri = 'https://o5x5jzoo7z.sse.codesandbox.io/graphql'; //our test Graphql Server which returns rates | |
const uri = 'https://localhost:5001/graphql'; | |
export function createApollo(httpLink: HttpLink, localStorage: LocalStorageService) { | |
const http = httpLink.create({ uri }); | |
const authLink = new ApolloLink((operation, forward) => { | |
// Get the authentication token from local storage if it exists | |
const token = localStorage.get('loginToken'); | |
// Use the setContext method to set the HTTP headers. | |
operation.setContext({ | |
headers: { | |
'Authorization': token ? `Bearer ${token}` : '' | |
} | |
}); | |
// Call the next link in the middleware chain. | |
return forward(operation); | |
}); | |
return { | |
link: authLink.concat(http), | |
cache: new InMemoryCache() | |
}; | |
} | |
@NgModule({ | |
exports: [ApolloModule, HttpLinkModule], | |
providers: [ | |
{ | |
provide: APOLLO_OPTIONS, | |
useFactory: createApollo, | |
deps: [HttpLink, LocalStorageService], | |
}, | |
], | |
}) | |
export class GraphQLModule {} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment