Angular 5中如何使用GET方法发送Apollo GraphQL查询
在Angular 5中使用Apollo GraphQL发送GET请求的解决方案
首先咱们先修正你代码里的一个小问题——你的GraphQL查询语句里重复写了query关键字,这会导致服务器无法正确解析查询。原代码里的内层query listSchemaAttributes是多余的,应该直接写字段名:
this.querySubscription = this.apollo.watchQuery<any>({ query: gql` query listSchemaAttributes($schemaDomain: String!) { listSchemaAttributes(schemaDomain: $schemaDomain) { type uniqueName isList } } `, variables: { schemaDomain: "abc", }, }) .valueChanges .subscribe(({data}) => { // 另外注意:你的原代码里用了data.currentUser,但查询的是listSchemaAttributes,这里要对应修改 this.schemaAttributes = data.listSchemaAttributes; });
接下来,要让Apollo发送GET请求而不是默认的POST,有两种配置方式,你可以根据需求选择:
方式一:全局配置所有查询使用GET请求
如果你希望所有的GraphQL请求都用GET,直接在Apollo客户端的HttpLink配置里指定method: 'GET'。通常这个配置在GraphQLModule(或你的Apollo配置文件)里:
import { NgModule } from '@angular/core'; import { ApolloModule, APOLLO_OPTIONS } from 'apollo-angular'; import { HttpLinkModule, HttpLink } from 'apollo-angular-link-http'; import { InMemoryCache } from 'apollo-cache-inmemory'; @NgModule({ imports: [ApolloModule, HttpLinkModule], providers: [ { provide: APOLLO_OPTIONS, useFactory: (httpLink: HttpLink) => { const link = httpLink.create({ uri: '你的GraphQL服务器端点URL', method: 'GET' // 全局设置默认请求方法为GET }); return { link, cache: new InMemoryCache(), }; }, deps: [HttpLink], }, ], }) export class GraphQLModule {}
方式二:仅针对特定查询使用GET请求
如果只想让这一个查询用GET,其他查询保持POST,可以通过设置请求上下文(context)来实现。
首先,确保你的Apollo客户端配置里已经添加了context链接(如果还没加的话):
// 在GraphQLModule中 import { setContext } from 'apollo-link-context'; import { HttpLinkModule, HttpLink } from 'apollo-angular-link-http'; import { ApolloModule, APOLLO_OPTIONS } from 'apollo-angular'; import { InMemoryCache } from 'apollo-cache-inmemory'; @NgModule({ imports: [ApolloModule, HttpLinkModule], providers: [ { provide: APOLLO_OPTIONS, useFactory: (httpLink: HttpLink) => { // 创建context链接,用于动态设置请求参数 const contextLink = setContext((_, { headers, method }) => { return { headers: { ...headers, }, method: method || 'POST' // 默认用POST,指定时用传入的method }; }); const httpLinkInstance = httpLink.create({ uri: '你的GraphQL服务器端点URL' }); const link = contextLink.concat(httpLinkInstance); return { link, cache: new InMemoryCache(), }; }, deps: [HttpLink], }, ], }) export class GraphQLModule {}
然后在你的组件调用watchQuery时,传入context并指定method: 'GET':
this.querySubscription = this.apollo.watchQuery<any>({ query: gql` query listSchemaAttributes($schemaDomain: String!) { listSchemaAttributes(schemaDomain: $schemaDomain) { type uniqueName isList } } `, variables: { schemaDomain: "abc", }, context: { method: 'GET' // 为这个查询单独设置GET请求 } }) .valueChanges .subscribe(({data}) => { this.schemaAttributes = data.listSchemaAttributes; });
最后要注意:你的GraphQL服务器必须支持GET请求,因为不是所有服务器默认开启这个支持。GET请求会把查询内容和变量编码到URL的查询参数中,服务器需要能正确解析这些参数。
内容的提问来源于stack exchange,提问作者devipriya
相关产品推荐
相关产品推荐

