打字稿传递函数作为参数

时间:2021-07-27 06:34:46

标签: angular typescript

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

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:1)

问题是,在 _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);
    });
  }