Angular。绑定Pubnub的消息

问题描述 投票:1回答:1

我正在使用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>

收到信息后,变量 msg 始终如一 app.component.html. 我不明白为什么会这样

请帮助我!

angular pubnub
1个回答
1
投票

问题出在函数范围上。在你的监听器中从标准函数改成箭头函数。

你有

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

将其改为使用箭头函数来固定范围。这个 关键字

    this.pubnub.addListener({
      ...
      message: (message) => {
        console.log(message);
        this.msg= message.message.content;
        console.log(this.msg);
      }
    });
© www.soinside.com 2019 - 2024. All rights reserved.