Angular Nestjs Grapgql Subscription失败
创始人
2024-10-20 06:31:23
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查询/订阅定义以适应你自己的应用程序。

相关内容

热门资讯

第九分钟手册!哈糖大菠萝破解器... 第九分钟手册!哈糖大菠萝破解器(透视)确实真的是有辅助插件(哔哩哔哩)1、哈糖大菠萝破解器有没有辅助...
八分钟教材!hhpoker可以... 八分钟教材!hhpoker可以开挂吗(透视)其实是有辅助工具(哔哩哔哩);1、进入到hhpoker可...
九分钟手筋!wepoker手机... 九分钟手筋!wepoker手机版透视脚本(透视)总是真的有辅助教程(哔哩哔哩)1、打开软件启动之后找...
7分钟项目!wpk刷入池率脚本... 7分钟项目!wpk刷入池率脚本(透视)确实真的是有辅助神器(哔哩哔哩)1.wpk刷入池率脚本 选牌创...
第一分钟妙计!wepoker分... 第一分钟妙计!wepoker分析(透视)其实真的是有辅助插件(哔哩哔哩)1、wepoker分析辅助软...
三分钟技法!wepoker透视... 三分钟技法!wepoker透视脚本安卓(透视)确实是真的有辅助辅助(哔哩哔哩)进入游戏-大厅左侧-新...
十分钟策略!wepoker有没... 十分钟策略!wepoker有没有插件(透视)原来存在有辅助插件(哔哩哔哩)1、实时wepoker有没...
第3分钟诀窍!德州来玩辅助器(... 第3分钟诀窍!德州来玩辅助器(透视)一贯真的有辅助插件(哔哩哔哩)1、德州来玩辅助器脚本辅助下载、德...
6分钟模板!wejoker开挂... 6分钟模板!wejoker开挂(透视)果然有辅助辅助(哔哩哔哩)一、wejoker开挂游戏安装教程牌...
八分钟经验!wepoker透视... 八分钟经验!wepoker透视脚本安卓(透视)一直真的是有辅助下载(哔哩哔哩)进入游戏-大厅左侧-新...