Reputation: 53
Am working on a chat application using NativeScript with Angular using a Firebase plugin. Am using the firebase event listener to listen for changes on a path like this:
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');
}
The problem is when I send a message from my end the view gets updated but when someone sends a message from their end the messages array changes but I don't see it unless I restart the application. What could be causing this.
Upvotes: 3
Views: 1922
Reputation: 1530
when you listen on the firebase event listener it run your code outside the angular zone. so basically you need to assign values to your variable inside NgZone.
Also running changeDetection cycle forcefully with the help of ChangeDetectionRef
using cd.detectChanges()
guaranties that changes reflected successfully. but you might not need to do this. do this only zone.run
doesn't work alone.
for example
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');
}
}
}
Upvotes: 5