当使用Apollo GraphQL与Angular一起使用时,可能会遇到头部信息未被传递的问题。这可以通过在Angular中设置请求中的头部信息来解决。以下是一个解决方法的代码示例:
import { ApolloModule, Apollo } from 'apollo-angular';
import { HttpLinkModule, HttpLink } from 'apollo-angular-link-http';
@NgModule({
imports: [
ApolloModule,
HttpLinkModule
],
...
})
export class AppModule {
constructor(apollo: Apollo, httpLink: HttpLink) {
// 设置GraphQL服务器的URL
const uri = 'https://example.com/graphql';
// 创建一个HttpLink实例并将其设置为Apollo的链接
const http = httpLink.create({ uri });
apollo.create({ link: http });
}
}
import { Apollo } from 'apollo-angular';
import gql from 'graphql-tag';
@Injectable({
providedIn: 'root'
})
export class MyService {
constructor(private apollo: Apollo) {}
myGraphQLQuery() {
const query = gql`
query {
// 查询内容
}
`;
// 设置请求头部信息
const headers = { 'Authorization': 'Bearer token' };
// 使用Apollo的watchQuery或query方法发送GraphQL请求
this.apollo.watchQuery({ query, variables: {}, context: { headers } })
.valueChanges.subscribe(result => {
// 处理结果
});
}
}
在上面的代码示例中,我们在Apollo的watchQuery或query方法中添加了一个context对象,其中包含了headers属性。这样就可以在发送GraphQL请求时传递头部信息。请根据实际情况修改代码中的GraphQL查询和头部信息。