使用的版本:
角度版本: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 {}
这里是我对需要有效JWT的受保护端点进行的graphql调用的精简版本。显然,此逻辑应该放在服务类中,但它至少将演示您的首页应如何与您的graphql模块类绑定,并将其注入到请求中。]
import { Component, OnInit } from '@angular/core';
import { Apollo } from 'apollo-angular';
import gql from 'graphql-tag';
@Component({
selector: 'app-user-profile',
templateUrl: './user-profile.component.html',
styleUrls: ['./user-profile.component.scss']
})
export class UserProfileComponent implements OnInit {
constructor(
private apollo: Apollo
) { }
user: any;
ngOnInit(): void {
this.apollo.query<any>({
query: gql`
query users {
loggedInUser {
email,
avatarUrl
}
}
`
}).subscribe(result => {
this.user = result.data.loggedInUser;
console.log(result);
});
}
}
这里是我的graphql模块,它与您的非常相似,除了我还包括了刷新令牌策略。
import { NgModule } from '@angular/core';
import { HttpLinkModule, HttpLink } from 'apollo-angular-link-http';
import { AuthenticationService } from './authentication/services/authentication.service';
import { ApolloLink } from 'apollo-link';
import { InMemoryCache } from 'apollo-cache-inmemory';
import { ApolloModule, APOLLO_OPTIONS } from 'apollo-angular';
import { onError } from 'apollo-link-error';
import { Observable } from 'apollo-link';
export function createApollo(httpLink: HttpLink, authenticationService: AuthenticationService) {
const authLink = new ApolloLink((operation, forward) => {
operation.setContext({
headers: {
Authorization: 'Bearer ' + localStorage.getItem('auth_token')
}
});
return forward(operation);
});
const errorLink = onError(({ forward, graphQLErrors, networkError, operation }) => {
if (graphQLErrors) {
if (graphQLErrors.some(x => x.message.toLowerCase() === 'unauthorized')) {
return promiseToObservable(authenticationService.refreshToken().toPromise()).flatMap(() => forward(operation));
}
}
});
return {
link: errorLink.concat(authLink.concat(httpLink.create({ uri: '/graphql' }))),
cache: new InMemoryCache(),
};
}
const promiseToObservable = (promise: Promise<any>) =>
new Observable((subscriber: any) => {
promise.then(
value => {
if (subscriber.closed) {
return;
}
subscriber.next(value);
subscriber.complete();
},
err => subscriber.error(err)
);
});
@NgModule({
exports: [ApolloModule, HttpLinkModule],
providers: [
{
provide: APOLLO_OPTIONS,
useFactory: createApollo,
deps: [HttpLink, AuthenticationService]
}
]
})
export class GraphqlModule { }