3

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.

6
  • Can you check output of NgZone.isInAngularZone() if put it front of this.message? Commented May 11, 2018 at 20:08
  • in front how? can you illustrate? Commented May 11, 2018 at 20:14
  • Of course. For example take.ms/euvJl Commented May 11, 2018 at 20:18
  • @yurzui its false Commented May 11, 2018 at 20:23
  • Try running code inside angular zone stackoverflow.com/questions/44086130/… Commented May 11, 2018 at 20:23

1 Answer 1

5

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');
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.