Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PubNub Angular2 AddListener - call function

Tags:

angular

pubnub

I am stuck on an addListener event. On receiving a message I want to call then call a function in my code but get the function not found error.

ERROR TypeError: this.plotBus is not a function

A very simple example.

   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")
 }
like image 990
ChrisR Avatar asked Aug 27 '26 06:08

ChrisR


1 Answers

The 'this' in traditional function does not work as you expect. A smart alternative to this issue is to use arrow function instead.

this.pubnub.addListener({
   message: msg=> {
       console.log(msg);
       this.plotBus(msg)
     }
  })
like image 195
siva636 Avatar answered Aug 30 '26 09:08

siva636



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!