【问题标题】:Add subscription to specific route in apollo client GraphQL React app在 apollo 客户端 GraphQL React 应用程序中添加对特定路由的订阅
【发布时间】:2020-01-30 18:49:53
【问题描述】:

我正在寻找一种解决方案,我可以将订阅添加到特定路由,而不是在应用启动时全局绑定订阅。

我知道订阅可以通过以下代码实现

const wsLink = new WebSocketLink({
  uri: `ws://localhost:4000`,
  options: {
    reconnect: true,
    connectionParams: {
      authToken: localStorage.getItem(AUTH_TOKEN),
    }
  }
})

const link = split(
  ({ query }) => {
    const { kind, operation } = getMainDefinition(query)
    return kind === 'OperationDefinition' && operation === 'subscription'
  },
  wsLink,
  authLink.concat(httpLink)
)

const client = new ApolloClient({
  link,
  cache: new InMemoryCache()
})

但是如果我添加这个,订阅会在页面加载时直接激活,而不管我在哪个页面上。

是否有任何解决方案可以让我在特定页面上绑定订阅而不是全局绑定。

【问题讨论】:

    标签: reactjs graphql apollo-client graphql-subscriptions


    【解决方案1】:

    如果您在查询参数中传递令牌并想要重新连接到链接,您需要做的就是通过重新分配来更新链接

    wsLink.subscriptionClient.url = `${GraphQLSocketURL}/query?authorization=${newAccessToken}`;
    

    如果您想在页面加载时建立连接,您只需将惰性标志设置为true

    const wsLink = new WebSocketLink({
      uri: `${GraphQLSocketURL}/query?authorization=${accessToken}`,
      options: {
        reconnect: true,
        reconnectionAttempts: 10,
        lazy: true,
      },
    });
    

    【讨论】:

      猜你喜欢
      • 2022-12-12
      • 2022-10-25
      • 2020-08-27
      • 2019-01-18
      • 2019-01-14
      • 2019-02-02
      • 2017-12-20
      • 2017-09-01
      • 2018-12-30
      相关资源
      最近更新 更多