我正在尝试使用 apollo websockets 检查互联网连接,这样做的目的是在没有连接时显示“您已断开连接”消息以防止用户输入并假设更改已保存(更改应该是保存在类型上),这是 apollo-link-ws 设置的一部分
const wsLink = new WebSocketLink({
uri: `ws://${hostname}${port ? `:${port}` : ''}/subscriptions`,
options: {
reconnect: true,
connectionParams: () => ({
authorization: localStorage.getItem('accelerator-token')
})
}
});
和
const hasSubscriptionOperation = ({ query: { definitions } }) =>
definitions.some(
({ kind, operation }) =>
kind === 'OperationDefinition' && operation === 'subscription'
);
这是客户端配置:
const client = new ApolloClient({
link: ApolloLink.split(
hasSubscriptionOperation,
wsLink,
ApolloLink.from([
cleanTypenameLink,
authMiddleware,
errorLink,
stateLink,
createUploadLink()
])
),
cache
});
最佳答案
经过一番搜索,我发现我可以使用 subscriptions-transport-ws 中的 SubscriptionClient
export const myClient = new SubscriptionClient(`ws://${hostname}${port ?
`:${port}` : ''}/subscriptions`, {
reconnect: true,
connectionParams: () => ({
authorization: localStorage.getItem('accelerator-token')
})
});
myClient.onConnected(()=>{console.log("connected f client f onConnected")})
myClient.onReconnected(()=>{console.log("connected f client f
reconnected")})
myClient.onReconnecting(()=>{console.log("connected f client f
reconnecting")})
myClient.onDisconnected(()=>{console.log("connected f client f
onDisconnected")})
myClient.onError(()=>{console.log("connected f client f onError")})
export const wsLink = new WebSocketLink(myClient);
这些方法可用于检测网络状态
关于websocket - 使用来自 apollo-link-ws 的 WebSocketLink 检查互联网连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50887793/