1

我是订阅设置,但 onNext 没有被触发我不知道为什么,因为这是我第一次实现订阅,文档对这个问题没有太大帮助。

以下是代码实现:

import {
  graphql,
  requestSubscription
} from 'react-relay'
import environment from '../network';

const subscription = graphql`
  subscription chatCreatedSubscription{
    chatCreated{
      id
      initiate_time
      update_time
      support_id
      category_id
      email
      name
    }
  }
  `;

function chatCreated(callback) {
  const variables = {};
  requestSubscription(environment, {
    subscription,
    variables,
    onNext: () => {
      console.log("onNext");
      callback()
    },
    updater: () => {
      console.log("updater");
    }
  });
}

module.exports = chatCreated;

这是我的订阅网络

import { Environment, Network, RecordSource, Store } from "relay-runtime";
import Expo from "expo";
import { SubscriptionClient } from "subscriptions-transport-ws";
import { WebSocketLink } from 'apollo-link-ws';
import { execute } from 'apollo-link';
import accessHelper from "../helper/accessToken";

const networkSubscriptions = async (operation, variables) => {
  let token = await accessHelper();
  if (token != null || token != undefined) {
    const subscriptionClient = new SubscriptionClient("ws://localhost:3000/graphql",
      {
        reconnect: true,
        connectionParams: {
          Authorization: token,
        },
      });
    execute(new WebSocketLink(subscriptionClient), {
      query: operation.text,
      variables,
    });
  }
}

const network = Network.create(fetchQuery, networkSubscriptions);
const store = new Store(new RecordSource());

const environment = new Environment({
  network,
  store
});

export default environment;

订阅在它执行的组件上的 componentDidMount 方法中调用,但是当新信息添加到订阅正在侦听的内容时,订阅中的 onNext 方法永远不会触发。

4

1 回答 1

0

所以我发现我的问题是网络 js 设置不正确和订阅传输 ws 的版本。我添加了包的 0.8.3 版本并对我的网络文件进行了以下更改:

const networkSubscriptions = async (config, variables, cacheConfig, observer) => {
  const query = config.text;
  let token = await accessHelper();
  if (token != null || token != undefined) {
    const subscriptionClient = new SubscriptionClient(`ws://${api}/graphql`,
      {
        reconnect: true,
        connectionParams: {
          Authorization: token,
        },
      });
    subscriptionClient.subscribe({ query, variables }, (error, result) => {
      observer.onNext({ data: result })
    })
    return {
      dispose: subscriptionClient.unsubscribe
    };
  }
}

如果您遇到与我相同的问题,我希望这对您有所帮助。

于 2019-02-26T10:55:35.787 回答