Angular: 来自 Pubnub 的绑定消息

Angular: Binding messages from Pubnub

我正在使用 PubNubAngular 从服务器接收消息。我成功收到消息,但我在 Angular 中的绑定不起作用。

这是我的函数:

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']
    });
  }
}

在我的 app.component.html:

<p>{{ msg }}</p>

收到消息后,变量msgapp.component.html中保持不变。我不明白这是为什么。

请帮帮我!

函数作用域有问题。在您的侦听器中从标准函数更改为箭头函数。

你有

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

将其更改为使用箭头函数来固定 this 关键字的范围

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