本文介绍了更新 apollo 客户端实例的 uri的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我们的一个项目中使用了 Angular Apollo.我正在创建阿波罗客户端:

I'm using Angular Apollo for one of our project. I'm creating the apollo client as:

this.apollo.create({
  link: this.httpLink.create({ uri: `${environment.apiBase}/graphql?access_token=${this.tokenService.token}`}),
  cache: new InMemoryCache()
 })

由于我们的 uri 有一个访问令牌,该令牌也会在某个时间点后过期,因此我们必须刷新它并获取新的访问令牌,因此是一个新的 uri.

Since our uri has an access token which also gets expired after a certain point of time, we had to refresh it and get the new access token, hence a new uri.

我在 apollo 文档中找不到任何关于更新 uri 的方法(也许我错过了?)存在.

I was unable find any method in apollo docs regarding the way to update the uri(maybe I've missed it out?), also if I create a new instance like that, it throws me an error that apollo client is already present.

有没有办法更新uri?

Is there any way to update the uri?

推荐答案

我知道它不是 Apollo Angular 文档的一部分(欢迎 PR!)但我在 apollo-angular-link-http 的 README 中描述了它.

I know it's not a part of Apollo Angular documentation (PR welcome!) but I described it in the README of apollo-angular-link-http.

有两种方式:

使用 Apollo Link 拦截查询并在上下文中设置 uri 属性

Use an Apollo Link to intercept the query and set uri property on the context

const authMiddleware = setContext((operation, { uri }) => {
  return refreshToken().then(res => ({
    uri: this.getURI()
  })
}))

或者使用 Angular 的 HttpClient 拦截器拦截请求并更改端点.

Or intercept the request with Angular's HttpClient interceptor and change the endpoint.

链接到包

这篇关于更新 apollo 客户端实例的 uri的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 11:02