angular - typescript 传递函数作为参数

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

最佳答案

问题是,在 _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/

相关文章:

Angular 2 指令及其属性

javascript - Angular2 rc1,shims_for_IE 在哪里

javascript - 路径或参数中不能有句点

node.js - Typescript + webpack(带热重载)+ NodeJS

javascript - Angular2 typescript 错误?

angular - 模块 '" "' 在 ionic 3 Geolocation 中没有导出成员 'NativeGeocoderReverseResult'

angular - 使用 ngFor 插入新输入时的焦点问题

javascript - 在 typescript 中映射类

javascript - "new"关键字只能调用void函数

javascript - 奇怪的 typescript 错误 :"the name g does not exist in the current scope"