繁体   English   中英

为什么我不能在订阅中调用方法 - 无法读取未定义的属性“showMessageFromSocket”

[英]Why i can't call method in subscribe - Cannot read property 'showMessageFromSocket' of undefined

我想在订阅块中调用方法,但我得到“无法读取未定义的属性'showMessageFromSocket'”。 如何调用方法 showMessageFromSocket? 在 angular 中是可能的。

export default class ConnectedChatroom extends Component<
  ConnectedChatroomProps,
  ConnectedChatroomState
> {
  wsObj: CompatClient;

  constructor(props: Props, context: *) {
    super(props, context);
    this.configureSocketChannel('dassfa')
  }

  showMessageFromSocket(message)  {
    console.log(message);
    //do something
  }

  configureSocketChannel(senderId: string) {
    let ws = Stomp.client("ws://localhost:8080/chat");
    ws.connect({}, function (frame) {
      ws.subscribe("/topic/messages", function (message) {
        this.showMessageFromSocket(message);
      });
    }, function (error) {
      console.log("STOMP error " + error);
    });
    this.wsObj = ws;
  }

使用arrow function 访问 class 成员,如没有自变量的 class 的变量或方法。

尝试如下

configureSocketChannel(senderId: string) {
    let ws = Stomp.client("ws://localhost:8080/chat");
    ws.connect({},  (frame) => {
      ws.subscribe("/topic/messages",  (message) => {
        this.showMessageFromSocket(message);
      });
    }, function (error) {
      console.log("STOMP error " + error);
    });
    this.wsObj = ws;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM