Angular Nestjs Grapgql Subscription失败
创始人
2024-10-20 06:31:26
0

在解决Angular Nestjs GraphQL Subscription失败的问题时,可以按照以下步骤进行操作:

  1. 确保你的Angular项目已经安装了apollo-angularsubscriptions-transport-ws依赖。你可以使用以下命令来安装它们:
npm install apollo-angular subscriptions-transport-ws
  1. 在你的Angular项目中创建一个GraphQL服务文件(通常命名为graphql.service.ts)来处理GraphQL订阅。下面是一个示例代码:
import { Injectable } from '@angular/core';
import { Apollo } from 'apollo-angular';
import { ApolloLink } from 'apollo-link';
import { HttpLink } from 'apollo-angular-link-http';
import { InMemoryCache } from 'apollo-cache-inmemory';
import { WebSocketLink } from 'apollo-link-ws';
import { getMainDefinition } from 'apollo-utilities';
import { split } from 'apollo-link';

@Injectable({
  providedIn: 'root'
})
export class GraphqlService {
  constructor(private apollo: Apollo) {
    this.initApollo();
  }

  initApollo() {
    const httpLink = new HttpLink({
      uri: 'http://localhost:3000/graphql' // 这里是你的Nestjs GraphQL服务的URL
    });

    const wsLink = new WebSocketLink({
      uri: 'ws://localhost:3000/graphql', // 这里是你的Nestjs GraphQL服务的WebSocket URL
      options: {
        reconnect: true
      }
    });

    const link = split(
      ({ query }) => {
        const { kind, operation }: any = getMainDefinition(query);
        return kind === 'OperationDefinition' && operation === 'subscription';
      },
      wsLink,
      httpLink
    );

    this.apollo.create({
      link: ApolloLink.from([link]),
      cache: new InMemoryCache()
    });
  }
}
  1. 在你的组件中使用该GraphQL服务来订阅数据。下面是一个示例代码:
import { Component, OnInit } from '@angular/core';
import { Apollo } from 'apollo-angular';
import gql from 'graphql-tag';

@Component({
  selector: 'app-my-component',
  template: `
    
  • {{ message.text }}
` }) export class MyComponent implements OnInit { messages: any; constructor(private apollo: Apollo) {} ngOnInit() { this.messages = this.apollo.subscribe({ query: gql` subscription { messageAdded { text } } ` }).map(res => res.data.messageAdded); } }

这些步骤将帮助你解决Angular Nestjs GraphQL Subscription失败的问题,并在你的应用中实现GraphQL订阅功能。请确保替换示例代码中的URL和GraphQL查询/订阅定义以适应你自己的应用程序。

相关内容

热门资讯

安装apache-beam==... 出现此错误可能是因为用户的Python版本太低,而apache-beam==2.34.0需要更高的P...
避免在粘贴双引号时向VS 20... 在粘贴双引号时向VS 2022添加反斜杠的问题通常是由于编辑器的自动转义功能引起的。为了避免这个问题...
Android Recycle... 要在Android RecyclerView中实现滑动卡片效果,可以按照以下步骤进行操作:首先,在项...
omi系统和安卓系统哪个好,揭... OMI系统和安卓系统哪个好?这个问题就像是在问“苹果和橘子哪个更甜”,每个人都有自己的答案。今天,我...
原生ios和安卓系统,原生对比... 亲爱的读者们,你是否曾好奇过,为什么你的iPhone和安卓手机在操作体验上有着天壤之别?今天,就让我...
Android - 无法确定任... 这个错误通常发生在Android项目中,表示编译Debug版本的Java代码时出现了依赖关系问题。下...
Android - NDK 预... 在Android NDK的构建过程中,LOCAL_SRC_FILES只能包含一个项目。如果需要在ND...
Akka生成Actor问题 在Akka框架中,可以使用ActorSystem对象生成Actor。但是,当我们在Actor类中尝试...
Agora-RTC-React... 出现这个错误原因是因为在 React 组件中使用,import AgoraRTC from “ago...
Alertmanager在pr... 首先,在Prometheus配置文件中,确保Alertmanager URL已正确配置。例如:ale...