Ionic3 firebase onSnapshot not update new message


#1

Hi guys! this function works on load but if someone sends a message, not update resolve(obj). what can I do.only working at startup Thanks.

readMessage(){
    this.getMessages().then((data) => {

  console.log(data); ////////only working at startup 
   
    })
    .catch();

  }
getMessages() : Promise<any>{
    return new Promise((resolve, reject) => {
    let obj: any = [];
    var UID = this.auth.getUid();

    this.vt.collection("message").bla bla bla..
    .onSnapshot(function(snapshot) {
      snapshot.docChanges().forEach(function(change) {

          if (change.type === "added" || change.type === "modified") {

            obj.push({
  
              bla bla bla
            ...
            ..
            .
            });

          }
         
          
        });
       

        resolve(obj);

     
      }, function (error) {
  
      });
   });

#2

you have a promise here… I believe you want to subscribe to the function that will detect the changes if it is an observable

this.messages$ = Observable.fromPromise(this.getMessages())


#3

I tried but it didn’t work. When I use promise, only working when loading but not change real time data.


#4

post the code that you tried?


#5

var message = Observable.fromPromise(this.getMessages())

console.log(message);


#6

I solved this issue. Promise does not supported onSnapshot realtime update. So I can be used observable.

getMessages(){
    return new Observable<any>(observer => {
    let obj: any = [];
    var UID = this.auth.getUid();

    this.vt.collection("messages")bla bla bla..
    .onSnapshot(function(snapshot) {
      snapshot.docChanges().forEach(function(change) {

          if (change.type === "added" || change.type === "modified") {

            obj.push({
  
            bla bla bla
     ....
     ..
     .
            });
          
          }
        
        });
       
      
        observer.next(obj);

      }, function (error) {
  
      });
    
    });
   
  }

if you want to subscribe realtime firebase data

 this.getMessages().subscribe(user => {
    
      return console.log(user); // read relatime data
  });

Thanks for aaronksaunders :grinning: