angular - 打字稿传递函数作为参数
问题描述
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.notificationWS.bind(this)
该函数时,它的返回值被传递给connectWebSocket
. 要访问指向您的函数的指针,请尝试以下操作:
this.apiService.connectWebSocket(this.notificationWS.bind);
如果您需要传递上下文,可以像这样引入第二个参数
connectWebSocket(func:Function, context: unknown) {
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(context));
});
}
// Call it like this
this.apiService.connectWebSocket(this.notificationWS.bind, this);
推荐阅读
- git - 解决很多简单的 git 冲突的最有效方法
- c# - 所需变量 Rest
- python - 如何使用 Pymongo 在 MongoDB 的 fs.chunks 集合中添加一个字段?
- reactjs - React Native Redux dispatch 不是函数,dispatch 是 Object 的一个实例
- android - 如何使用 Espresso 测试片段?
- java - curl数据中的字符串“%20”是什么?
- python - OpwenWrt - 使用 Python 从 SPI 读取字节
- javascript - 在Angular中,当我们单击编辑选项时如何加载单选按钮值
- react-native - 我可以添加 backgroundColor 作为自定义道具来反应原生元素按钮吗?
- java - Retrofit 2 在请求数据中命名变量时添加 java 类名