要在没有StompJS的情况下实现WebSocket,可以使用Angular的内置WebSocket模块。
首先,安装WebSocket模块:
npm install @angular/websocket
接下来,创建一个WebSocket服务:
websocket.service.ts:
import { Injectable } from '@angular/core';
import { webSocket, WebSocketSubject } from 'rxjs/webSocket';
@Injectable({
providedIn: 'root'
})
export class WebSocketService {
private subject: WebSocketSubject;
constructor() { }
connect(url: string): WebSocketSubject {
if (!this.subject || this.subject.closed) {
this.subject = webSocket(url);
}
return this.subject;
}
send(message: any): void {
if (this.subject) {
this.subject.next(message);
}
}
close(): void {
if (this.subject) {
this.subject.complete();
}
}
}
然后,在你的组件中使用WebSocket服务:
app.component.ts:
import { Component, OnInit } from '@angular/core';
import { WebSocketService } from './websocket.service';
@Component({
selector: 'app-root',
template: `
`
})
export class AppComponent implements OnInit {
constructor(private webSocketService: WebSocketService) { }
ngOnInit(): void {
this.connectToWebSocket();
}
connectToWebSocket(): void {
const url = 'wss://your-websocket-url';
const webSocket = this.webSocketService.connect(url);
webSocket.subscribe(
(message) => {
console.log('Received message:', message);
},
(error) => {
console.error('WebSocket error:', error);
},
() => {
console.log('WebSocket connection closed');
}
);
}
sendMessage(): void {
const message = 'Hello WebSocket!';
this.webSocketService.send(message);
}
}
在上面的示例中,我们创建了一个WebSocketService来管理WebSocket连接和发送消息。在AppComponent中,我们在ngOnInit方法中调用connectToWebSocket方法来连接到WebSocket服务器,并在sendMessage方法中发送消息。
这样就可以在没有StompJS的情况下使用Angular实现WebSocket通信了。
上一篇:Angular 10 - 如何在集合更改时自动加载新项目
下一篇:Angular 10 - 什么是错误:R3InjectorError(AppModule)[Window -> Window -> Window]