【问题标题】:PubNub Angular2 AddListener - call functionPubNub Angular2 AddListener - 调用函数
【发布时间】:2018-05-05 03:08:45
【问题描述】:

我遇到了一个 addListener 事件。在收到一条我想调用的消息时,然后在我的代码中调用一个函数,但得到函数未找到错误。

ERROR TypeError: this.plotBus 不是函数

一个非常简单的例子。

   this.pubnub.publish({
    channel: 'test',
    message:["hello"]
    })

 this.pubnub.addListener({
   message: function(msg) {
       console.log(msg);
       this.plotBus(msg)
     }
  })

 this.pubnub.subscribe({
     channels: ['test'],
     triggerEvents: ['message']
 });

plotBus(bus){
   console.log("Plotting Bus with received data")
 }

【问题讨论】:

  • 你需要把你的plotBus函数放在最上面。

标签: angular pubnub


【解决方案1】:

传统函数中的 'this' 无法按预期工作。这个问题的一个聪明的替代方法是使用箭头函数。

this.pubnub.addListener({
   message: msg=> {
       console.log(msg);
       this.plotBus(msg)
     }
  })

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-05
    • 2015-05-13
    • 2017-07-08
    • 1970-01-01
    • 1970-01-01
    • 2018-02-04
    相关资源
    最近更新 更多