如何在全局范围内知道 ApolloClient 中所有查询的 networkStatus? [英] How can I know the networkStatus of all queries in ApolloClient globally?

查看:22
本文介绍了如何在全局范围内知道 ApolloClient 中所有查询的 networkStatus?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 networkStatus 处于运行状态时显示预加载器.

I am trying to show preloader when a networkStatus is in-flight.

我知道每个查询都会返回它自己的 networkStatus,但是在我的应用程序中有很多不同的查询.我想有一种方法可以在全局范围内处理所有查询的所有 networkStatus.

I know that every query returns its own networkStatus, but in my application there are so many different queries. I want to have a way of handling all the networkStatus for all the queries, globally.

我想知道代码中的答案是:网络上是否有任何待处理的查询?".

What I'm wanting to know inside my code is the answer for: "Is there any query pending on the network?".

推荐答案

目前,没有办法做到这一点,至少不容易/内置.您可以在 https://github.com/apollographql/apollo-feature- 上将此作为功能请求请求.

Currently, there's no way of doing that, at least not easily/built-in. You could request this as a feature on https://github.com/apollographql/apollo-feature-requests.

根据您想要实现的目标,在您的 HttpLink 上使用中间件/后件就足够了,例如:

Depending on what you are wanting to achieve, using a middleware/afterware on your HttpLink could be sufficient, e.g:

import { ApolloLink } from 'apollo-link';

const middleware = new ApolloLink((operation, forward) => {
  console.log('Starting', operation);

  return forward(operation);
});

const afterware = new ApolloLink((operation, forward) => {
  return forward(operation).map(response => {
    console.log('Completed', operation);

    return response;
  });
});

const client = new ApolloClient({
  cache: new InMemoryCache(),
  link: ApolloLink.from([
    middleware,
    afterware,
    new HttpLink({ ... }),
  ]),
});

middleware 将在每个请求之前被调用,而 afterware 将在之后被调用.您可以在以下位置阅读有关链接的更多信息:https://www.apollographql.com/docs/link/.

The middleware will be called before each request, and the afterware, after. You can read more about links at: https://www.apollographql.com/docs/link/.

或者,查看 Apollo 公开公开的一些 API,我能够以这种非官方"方式进行检查:

Alternatively, looking at some of the APIs that Apollo exposes publicly, I was able to make the check on this "unofficial" way:

function queriesInFlight() {
  // client is your ApolloClient instance
  const { queryManager } = client;

  return Object.keys(queryManager.queryStore.getStore()).filter(queryId =>
    queryManager.checkInFlight(queryId),
  );
}

这篇关于如何在全局范围内知道 ApolloClient 中所有查询的 networkStatus?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆