要给出"阿波罗 v2 订阅 GraphQL"包含代码示例的解决方法,首先需要明确阿波罗 v2是指Apollo Client的第二个版本,它支持在GraphQL应用程序中进行订阅操作。
以下是一个使用Apollo Client v2进行GraphQL订阅的代码示例:
npm install apollo-client apollo-link apollo-link-http apollo-link-ws apollo-utilities subscriptions-transport-ws graphql graphql-tag
import { ApolloClient } from 'apollo-client';
import { InMemoryCache } from 'apollo-cache-inmemory';
import { HttpLink } from 'apollo-link-http';
import { WebSocketLink } from 'apollo-link-ws';
import { split } from 'apollo-link';
import { getMainDefinition } from 'apollo-utilities';
const httpLink = new HttpLink({
uri: 'http://localhost:4000/graphql', // 替换为你的GraphQL服务器端点
});
const wsLink = new WebSocketLink({
uri: 'ws://localhost:4000/graphql', // 替换为你的GraphQL WebSocket端点
options: {
reconnect: true,
},
});
const link = split(
({ query }) => {
const definition = getMainDefinition(query);
return (
definition.kind === 'OperationDefinition' &&
definition.operation === 'subscription'
);
},
wsLink,
httpLink,
);
const client = new ApolloClient({
link,
cache: new InMemoryCache(),
});
import gql from 'graphql-tag';
const MESSAGE_SUBSCRIPTION = gql`
subscription MessageSubscription {
message {
id
content
createdAt
}
}
`;
const subscription = client.subscribe({ query: MESSAGE_SUBSCRIPTION });
subscription.subscribe({
next(response) {
console.log(response.data.message);
},
error(err) {
console.error('订阅失败:', err);
},
});
以上代码示例演示了如何使用Apollo Client v2进行GraphQL订阅。你需要替换示例中的GraphQL服务器端点和WebSocket端点为你自己的值,以便与你的GraphQL服务器进行通信。
上一篇:阿波罗 HttpLink 异步