【问题标题】:angular view not updating when data changes数据更改时角度视图不更新
【发布时间】:2018-05-11 20:06:17
【问题描述】:

我正在使用带有 Firebase 插件的 NativeScript 和 Angular 开发一个聊天应用程序。 我正在使用 firebase 事件侦听器来侦听这样的路径上的更改:

firebase.addValueEventListener( (result) => {
  for(var key in result.value){
    this.posts.push(result.value[key].Message);
  }
  this.messages = this.posts;
  //am using this.messges to update the view
  this.posts=[];


  }, '/forum/messages');
}

问题是当我从我端发送消息时,视图会更新,但是当有人从他们端发送消息时,消息数组会发生变化,但除非我重新启动应用程序,否则我看不到它。 这可能是什么原因造成的。

【问题讨论】:

标签: angular angular2-nativescript


【解决方案1】:

当您侦听 firebase 事件侦听器时,它会在角度区域之外运行您的代码。所以基本上你需要在 NgZone 中为你的变量赋值。

还在ChangeDetectionRef 的帮助下强制运行changeDetection 循环,使用cd.detectChanges() 保证更改成功反映。但您可能不需要这样做。只这样做zone.run 不能单独工作。

例如

import {
    NgZone,
    ChangeDetectorRef
} from "@angular/core";
@Component({
    selector: "Home",
    moduleId: module.id,
    templateUrl: "./home.component.html",
    styleUrls: ["./home-common.css", "./home.css"]
})
export class HomeComponent{
    messages=[];
    constructor(
        private cd: ChangeDetectorRef,
        private zone: NgZone
    ) {
        firebase.addValueEventListener( (result) => {


          for(var key in result.value){
            this.posts.push(result.value[key].Message);
          }
          this.zone.run(() => {
              this.messages = this.posts;
              this.cd.detectChanges();
          })

          //am using this.messges to update the view
          this.posts=[];


          }, '/forum/messages');
        }
    }
}

【讨论】:

  • 工作得很好。谢谢!
猜你喜欢
  • 2020-12-17
  • 1970-01-01
  • 1970-01-01
  • 2018-04-02
  • 1970-01-01
  • 1970-01-01
  • 2015-01-07
  • 2016-12-18
相关资源
最近更新 更多