I'm using PubNubAngular to receive messages from Server. I received messages successfully but my binding in Angular is not working.
Here's my function:
import { Component, OnInit } from '@angular/core';
import { PubNubAngular } from 'pubnub-angular2';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss'],
providers: [PubNubAngular]
})
export class AppComponent implements OnInit {
title = 'GDentalv2';
private publishkey = '';
private subscribekey = '';
public msg: string = "";
constructor(public pubnub: PubNubAngular) {
}
ngOnInit() {
this.pubnubInit();
}
pubnubInit() {
this.pubnub.init({
publishKey: this.publishkey,
subscribeKey: this.subscribekey,
ssl: true,
uuid: "client"
});
this.pubnub.addListener({
status: function (st) {
if (st.category === "PNConnectedCategory") {
// this.pubnub.publish({
// message: 'Hello from the PubNub Angular2 SDK!',
// channel: 'pubnub_onboarding_channel'
// });
}
},
message: function (message) {
console.log(message);
this.msg= message.message.content;
console.log(this.msg);
}
});
this.pubnub.subscribe({
channels: ['pubnub_onboarding_channel'],
withPresence: true,
triggerEvents: ['message', 'presence', 'status']
});
}
}
In my app.component.html
:
<p>{{ msg }}</p>
After receiving the message, the variable msg
remains unchanged in app.component.html
. I don't understand why that is.
Please help me!
Problem is with function scope. Change from standard functions to arrow function in your listener.
You have
this.pubnub.addListener({
...
message: function (message) {
console.log(message);
this.msg= message.message.content;
console.log(this.msg);
}
});
Change it to use arrow functions to fix scope of this keyword
this.pubnub.addListener({
...
message: (message) => {
console.log(message);
this.msg= message.message.content;
console.log(this.msg);
}
});