简体   繁体   English

Apollo HttpLink 异步

[英]Apollo HttpLink Async

For the following code:对于以下代码:

const apolloClient = new ApolloClient({
  cache: new InMemoryCache(),
  link: new HttpLink({
    uri: endpoint,
    headers: {
      'Content-Type': 'application/json',
      Authorization: `Bearer ${token}`
    }
  })
});

I need to get endpoint and token asynchronously.我需要异步获取endpointtoken How may I do this?我该怎么做?

Thank you谢谢

You can use apollo-link-context to modify your requests.您可以使用apollo-link-context来修改您的请求。 You can cache the values as shown if you don't fetch them on every request.如果您不在每个请求中都获取它们,则可以缓存如图所示的值。

let token
let uri
const contextLink = setContext(async () => {
  if (!token) {
    token = await getTokenAsync()
  }
  if (!uri) {
    uri = await getUriAsync()
  }

  return { uri, token }
});

const client = new ApolloClient({
  ...
  link: ApolloLink.from([
    contextLink,
    httpLink,
  ])
})

The above is the preferred way of dynamically setting these parameters.以上是动态设置这些参数的首选方式。 Alternatively, you could just fetch the token and URI before rendering your ApolloProvider and then dynamically create your client instance based on the values.或者,您可以在呈现 ApolloProvider 之前获取令牌和 URI,然后根据这些值动态创建客户端实例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM