在解决Angular Nestjs GraphQL Subscription失败的问题时,可以按照以下步骤进行操作:
apollo-angular
和subscriptions-transport-ws
依赖。你可以使用以下命令来安装它们:npm install apollo-angular subscriptions-transport-ws
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()
});
}
}
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查询/订阅定义以适应你自己的应用程序。