首页 > 解决方案 > 打字稿传递函数作为参数

问题描述

  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 函数,但消息为空

标签: angulartypescript

解决方案


问题是,当使用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);

推荐阅读