如何从 UI (Angular) 上的 Apollo Client 验证 GraphQL 订阅是否已成功连接?或者如果它意外断开连接?

问题描述

我有一个基于 Angular 的 UI 应用程序,可与基于 Django 的 GrpahQL API 配合使用。我订阅了所有实体,这些实体将自动数据库更新推送到 UI。我正在寻找一种方法来在我的 Angular 代码中知道使用 websocket 连接的订阅查询是否已成功进行。而且,如果它以某种方式断开连接,我希望立即收到通知,以便我可以尝试重新建立连接。但截至目前,当 Apollo 订阅连接或间歇性失败时,我没有看到它有任何变化。

这是我的代码:-

  subscribetoMembers() {
    console.log('Attempting to subscribe');
    if (!this.membeRSSubscribed) {
      this.apollo
        .subscribe({
          query: SUBSCRIPTIONS.user,})
        .subscribe((result: any) => {
          console.log('member subscription result ',{
            members: state.members,result,});
          this.membeRSSubscribed = true // <==== Looks like this never gets executed upon connection. It only gets here after the first update is sent from the db
        });
    }
  }

这就是我构建 ApolloClient 的方式,如果有帮助的话:-

import { Component,NgModule } from '@angular/core';
import { APOLLO_OPTIONS } from 'apollo-angular';
import {
  ApolloClientOptions,ApolloLink,DefaultOptions,InMemoryCache,split,} from '@apollo/client/core';
import { HttpLink } from 'apollo-angular/http';
import { environment } from 'src/environments/environment';
import { WebSocketLink } from '@apollo/client/link/ws';
import { getMainDeFinition } from '@apollo/client/utilities';
import { AUTH_TOKEN_KEY } from '../../common/constants';
import { Select } from '@ngxs/store';
import { AuthState } from '../../state/auth/auth.state';
import { Observable } from 'rxjs';

const uri = environment.graphql_endpoint;
let token = localStorage.getItem(AUTH_TOKEN_KEY);

let ws = new WebSocketLink({
  uri: `${environment.websocket_graphql_endpoint}?token=${token}`,options: {
    reconnect: true,},});

export function createApollo(httpLink: HttpLink) {
  const http = httpLink.create({
    uri,// withCredentials: true,});

  /**
   * Split the Apollo link to route differently based on the operation type.
   */
  const link: ApolloLink = split(
    // split based on operation type
    ({ query }) => {
      let deFinition = getMainDeFinition(query);
      return (
        deFinition.kind === 'OperationDeFinition' &&
        deFinition.operation === 'subscription'
      );
    },ws,http
  );

  const opts: ApolloClientOptions<any> = {
    link,cache: new InMemoryCache(),// defaultOptions,};

  return opts;
}

@NgModule({
  providers: [
    {
      provide: APOLLO_OPTIONS,useFactory: createApollo,deps: [HttpLink],],})
export class GraphQLModule {}

我的问题 - 在上面的 subscribetoMembers 方法中,如何在成功连接后立即知道与服务器的 websocket 连接已成功建立,以便我可以立即更新 membeRSSubscribed 布尔值。我正在使用该布尔值来不尝试重新尝试连接。此外,如果与服务器的 websocket 连接以某种方式失败,我想从 subscribetoMembers 方法中检测它,以便我可以尝试从那里重新连接。

希望这很清楚。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)