angular - StompJS Websocket 已连接但不返回任何消息
问题描述
我正在尝试与@stomp/stompjs 进行websocket 连接,尽管在控制台中连接成功,但数据没有更新,任何关于我做错了什么的想法,我已经在线阅读了所有内容,但我没有不明白为什么它不起作用。
import { Component, OnDestroy, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { Stomp } from '@stomp/stompjs';
import * as SockJS from 'sockjs-client';
import { MessagesService } from 'src/app/services/messages.service';
@Component({
selector: 'app-classtwo',
templateUrl: './classtwo.component.html',
styleUrls: ['./classtwo.component.scss']
})
export class ClasstwoComponent implements OnInit, OnDestroy {
public mail_list:any [] = []
private stompClient = Stomp.over(new SockJS('http://localhost:8080/mailbot-websocket'));
constructor(private service:MessagesService, private router: Router) { }
ngOnInit(): void {
this._loadEmailsFromRestApi()
this._loadEmailsFromWebSocket()
}
private _loadEmailsFromWebSocket() {
let that = this;
this.stompClient.connect({}, () =>{
that.stompClient.subscribe('/topic/processed/TYPE_II', this.callback)
})
}
private _loadEmailsFromRestApi() {
this.service.getPendingMailsByCategory('TYPE_II').subscribe( res => {
this.mail_list = res
})
}
ngOnDestroy(): void {
if (this.stompClient != null) {
this.stompClient.disconnect(()=> {
console.log("DISCONECTED");
});
}
}
goToMailDescription(category:string, id:string) {
this.router.navigate(['/mailDetail/' + category + '/' + id]);
}
callback = (message:any) => {
if(message.body)
this.mail_list = JSON.parse(message.body)
}
}
注意:似乎在重新加载页面后它会收到该消息,但只有在您继续运行它的情况下它是相同的,直到再次重新加载。
解决方案
声明 stomp 客户端如下
public stompClient: CompatClient | undefined
然后初始化它并在 init 部分中调用它
ngOnInit() { this.initWebsocket() }
initWebsocket(){
let ws:WebSocket = new SockJS(`${DOMAIN_URL}`);
this.stompClient = Stomp.over(ws);
const that = this;
this.stompClient.connect({}, (frame:any) => {
if(!that.stompClient){
return;
}
this._subcribeTopic(`${TOPIC_URL}`);
});
}
然后只需添加订阅方法并根据需要执行其余操作,这是一个示例
private _subcribeTopic(topic: string) {
if(!this.stompClient){
console.error("Error to configure websocket");
return;
}
// You could add something like a switch statement here in case you have more than one topic
this.stompClient.subscribe(topic, (message:any) => {
if (message.body) {
let model: any = JSON.parse(message.body);
this._updateWebSocketResponse(model);
}
});
}
private _updateWebSocketResponse (response:any) {
console.log(response)
}
我会建议停止 websocket 连接到垃圾收集器,但这真的取决于你
ngOnDestroy() { this.stompClient.disconnect() }
推荐阅读
- php - AWS:PHP 代码是可见的,而不是在虚拟主机中执行它
- javascript - 我在将 hashMap String 发送到服务器 php 时遇到问题,而不是在 volly 响应 android 中返回 JsonArray
- java - java 如何对列表中最早的时间戳进行排序?
- c - 我写了 RegCreateKeyEx () 但它失败了。它的原因是什么?
- javascript - Node.js 请求使用“请求”模块,但不适用于“axios”
- hibernate - 我需要将哪些 c3p0 属性用于休眠池?
- php - 为什么在我可以将代码放入文件时使用特征
- python - _csv.Error:在将 csv 转换为 excel 时,python 中的行包含 NULL 字节
- node.js - Google 助理的网络抓取响应错误
- android - 查询子集合 firestore 中的文档