1

I'm working on Ionic and using Angular firestore with offline persitence. While being online, i can do something in 'then' brackets but while being offline nothing happens.

The add or update method works in both cases but i need some callback to inform the user. The only way i found was to subscribe in the constructor. Question : Is there another best way ?

import { AngularFirestore, AngularFirestoreCollection } from 'angularfire2/firestore';
...

export class MyPage {

  placeRef: AngularFirestoreCollection<Place>;

constructor(... public afs: AngularFirestore) {
this.placeRef.valueChanges()
      .subscribe(actions => {

        if (this.totPlaces < actions.length && this.totPlaces != 0) { this.onUploadComplete(); }
        this.totPlaces = actions.length;


      })
}

updateName(dataObj: any): Promise<any> {

    return new Promise((resolve, reject) => {
      this.afs
        .collection("collection-id")
        .doc("doc-id")
        .update(dataObj)
        .then((obj: any) => {
          resolve(obj);
          console.log("ok modified");
        })
        .catch((error: any) => {
          console.log("nok error");
          reject(error);

        });
    });
  }

...

this.placeRef = this.afs.collection<Place>("collection-id");
addPlace() {

      let d = new Date();
      let nd = new Date(d.getTime());

      this.placeRef.add({
        name: ...,
        note: ...,
        ...
      })
      /* see workaround "this.placeRef.valueChanges"
        .then((docRef) => {
          // only if mobile datas or wifi enabled
          console.log("Document written with ID: ", docRef.id);

          //this.onUploadComplete();

        }).catch((error) => {

          console.error("Error adding document: ", error);
        });*/

  }

}

1 Answers1

0

You can create a function that always returns a promise like this.

add(data: any): Promise<any> {

 let obj = collection.add({
   ...data
 });
 // If internet connection is available
 if(navigator.onLine && obj instanceof Promise && typeof obj.then === 'function') {
   return obj;
 }
 else {
  return new Promise((resolve, reject) => {
    resolve({action: 'ADD', mode: 'offline'});
  });
 }
}

You must test 'obj' variable to know if it's a promise and has 'then' function.

Gratien Asimbahwe
  • 1,606
  • 4
  • 19
  • 30
tcheck
  • 1