0

我尝试在我的 Angular Web 项目中使用 vertx-eventbus-client.js 3.8.3。以下工作正常:

declare const EventBus: any;`

@Injectable({`
    providedIn: 'root'
})
export class DeviceService implements OnInit {

    constructor(private httpClient: HttpClient) {

       var eb = new EventBus("http://127.0.0.1:8080/eventbus");

       eb.onopen = function() {

          eb.registerHandler("events-feed", function(error, message) {
              console.log("Message: " + message.body);
          });

          eb.registerHandler("receiver", function(error, message) {
             console.log('Message: ' + message.body);
          });

          eb.publish("events-feed", "Test", function (error, message) {
              console.log(JSON.parse(message.body));
          });
      }

    }



}

将建立与后端的连接,我通过 registerHandler 方法接收消息。但是当我在这样的函数中移动代码时:

private eb : any;

initializeEventBus() {


 this.eb = new EventBus("http://127.0.0.1:8080/eventbus");

       this.eb.onopen = function() {

          this.eb.registerHandler("events-feed", function(error, message) {
              console.log("Message: " + message.body);
          });

          this.eb.registerHandler("receiver", function(error, message) {
             console.log('Message: ' + message.body);
          });

          this.eb.publish("events-feed", "Test", function (error, message) {
              console.log(JSON.parse(message.body));
          });
      }

    }

}

它出错并引发以下错误:

core.js:14597 ERROR TypeError: Cannot read property 'registerHandler' of undefined
    at EventBus.DeviceService.eb.onopen (device.service.ts:28)
    at w.self.sockJSConn.onopen (vertx-eventbus.js:121)
    at w.r.dispatchEvent (eventtarget.js:51)
    at w._open (main.js:320)
    at w._transportMessage (main.js:253)
    at u.i.emit (emitter.js:50)
    at WebSocket.ws.onmessage [as __zone_symbol__ON_PROPERTYmessage] (websocket.js:35)
    at WebSocket.wrapFn (zone.js:1332)
    at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:423)
    at Object.onInvokeTask (core.js:16147)

你知道我做错了什么吗?

问候

4

1 回答 1

1

由于您使用的是 this 关键字,因此它没有被绑定。要使其工作,您需要使用如下箭头功能。

this.eb.onopen = () => {

          this.eb.registerHandler("events-feed", (error, message) => {
              console.log("Message: " + message.body);
          });

          this.eb.registerHandler("receiver",  (error, message) => {
             console.log('Message: ' + message.body);
          });

          this.eb.publish("events-feed", "Test",  (error, message) => {
              console.log(JSON.parse(message.body));
          });
      }

希望这可以帮助。

于 2019-11-19T16:13:29.930 回答