【发布时间】:2020-09-09 11:32:36
【问题描述】:
使用的版本:
Angular 版本:8.3 阿波罗客户端:2.6.0
我正在尝试将 graphql 与授权的 jwt 令牌一起使用。登录后令牌在本地存储中设置。
登录时,主页会在执行 gql 查询的位置加载,但是,由于在应用加载时导入了 graphql.module.ts,因此令牌在加载时不可用。有没有办法修改这个模块?参考链接是here
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 } from 'apollo-link';
import { setContext } from 'apollo-link-context';
const uri = '/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 link = ApolloLink.from([basic, auth, httpLink.create({ uri })]);
const cache = new InMemoryCache();
return {
link,
cache
}
}
@NgModule({
exports: [
HttpClientModule,
ApolloModule,
HttpLinkModule
],
providers: [{
provide: APOLLO_OPTIONS,
useFactory: provideApollo,
deps: [HttpLink]
}]
})
export class GraphQLModule {}
【问题讨论】:
-
我的设置与您的非常相似。您是否将
GraphQLModule包含在 app.module.ts 上的导入数组中?这适用于我的情况,在我的本地存储中设置令牌后,我可以为所有后续调用注入令牌。 -
你能在你的主页上展示你用来调用graphQL的代码吗?
标签: angular authentication graphql apollo