connectWebSocket() {
const socket = new SockJS('http://localhost:8080/websocket');
this.stompClient = Stomp.over(socket);
const _this = this;
this.stompClient.connect({ "Authorization" : "Bearer "+localStorage.getItem("Authorization")}, function (frame) {
_this.stompClient.subscribe('/user/queue/notification',function (message) {
const body = JSON.parse(message.body);
console.log(body)
});
});
}
这就是我当前连接到 websocket 的方式,但我想实现这样的目标 connectWebSocket(func:Function) {
const socket = new SockJS('http://localhost:8080/websocket');
this.stompClient = Stomp.over(socket);
const _this = this;
this.stompClient.connect({ "Authorization" : "Bearer "+localStorage.getItem("Authorization")}, function (frame) {
_this.stompClient.subscribe('/user/queue/notification',func());
});
}
然后像这样调用它 notificationWS(hello){
const body = JSON.parse(hello.body);
if(body.notificationType==="FOLLOW"){
console.log(body)
}
}
this.apiService.connectWebSocket(this.notificationWS.bind(this));
所以我想将函数作为参数传递给 ws 函数,但消息为空
最佳答案
问题是,在 _this.stompClient.subscribe('/user/queue/notification',func());
它需要一个函数作为第二个参数。相反,您已经使用 func()
调用了该函数。并传递返回值。
试试这个( func
而不是 func()
):
connectWebSocket(func:Function) {
const socket = new SockJS('http://localhost:8080/websocket');
this.stompClient = Stomp.over(socket);
const _this = this;
this.stompClient.connect({ "Authorization" : "Bearer "+localStorage.getItem("Authorization")}, function (frame) {
_this.stompClient.subscribe('/user/queue/notification',func);
});
}
关于angular - typescript 传递函数作为参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68540012/