Angular 数据更改时角度视图不更新

Angular 数据更改时角度视图不更新,angular,angular2-nativescript,Angular,Angular2 Nativescript,我正在使用NativeScript和Firebase插件开发聊天应用程序。 我正在使用firebase事件侦听器侦听以下路径上的更改: firebase.addValueEventListener( (result) => { for(var key in result.value){ this.posts.push(result.value[key].Message); } this.messages = this.posts; //am using this.m

我正在使用NativeScript和Firebase插件开发聊天应用程序。 我正在使用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');
}
问题是,当我从我的终端发送消息时,视图会更新,但当有人从他们的终端发送消息时,消息数组会更改,但除非我重新启动应用程序,否则我看不到它。
这可能是什么原因造成的。

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

同时,在
ChangeDetectionRef
的帮助下,使用
cd强制运行changedetectioncycle。detectChanges()
可确保成功反映更改。但你可能不需要这样做。仅在
区域执行此操作。单独运行
不起作用

比如说

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

如果将
NgZone.isInAngularZone()
放在这条消息的前面,您能检查它的输出吗?如何放在前面?你能举例说明吗?当然可以。例如@yurzui,它在angular zone中运行的错误代码非常有效。非常感谢。