【问题标题】:Angular: Binding messages from PubnubAngular:绑定来自 Pubnub 的消息
【发布时间】:2020-05-05 04:59:25
【问题描述】:

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

收到消息后,app.component.html中的变量msg保持不变。我不明白为什么会这样。

请帮帮我!

【问题讨论】:

  • 您能否提供您正在使用的 PubNub SDK 版本以及您所关注代码的链接是什么?
  • 你能把所有的组件代码贴出来吗?
  • Raz 所说的 ^^^。我认为我们需要更多的上下文。有关详细信息,请参阅此链接:pubnub.com/docs/angularjs-javascript/pubnub-javascript-sdk
  • 此组件或其其中一个祖先是否正在实施 OnPush 策略?
  • 抱歉我来晚了,我刚刚更新了我的component.ts。这就是我的所有组件,我遵循了文档pubnub.com/docs/angular2-javascript/…

标签: angular pubnub


【解决方案1】:

问题在于函数范围。在侦听器中从标准函数更改为箭头函数。

你有

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

【讨论】:

  • 谢谢!,它的工作^^,但我还是不明白这个
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-27
  • 2017-10-12
相关资源
最近更新 更多