Search code examples
google-cloud-firestoreangular2-observablesangularfire5

Share FireStoreCollection to serveral views


im having an ionic project with a firestore backend using 'angularfire2/firestore'. To share a collection between views i created a firebaseservice provider:

      interface if_friend {
             name: string;
             email: string;
             id?: any;
       }

     friendsCollection: AngularFirestoreCollection<if_friend>;
     friends$: Observable<if_friend[]>;

  constructor(public afStore: AngularFirestore) {
    console.log('Hello FirebaseServiceProvider Provider');
    this.friendsCollection = afStore.collection('/[email protected]/Friends/friends/');
    this.friends$ = this.friendsCollection.valueChanges();
  }

  getFriends(){
   return this.friends$;
  }

On the constructor of the views im getting the Obserable like this:

public friends$: Observable<if_friend[]>;

constructor(public navCtrl: NavController, public firebaseService: FirebaseServiceProvider) {
  this.friends$ = this.firebaseService.getFriends();
}

and using it in the html file with the async pipe:

 <ion-list>
      <ion-item *ngFor="let friend of friends$ | async">

This works well for the first view im entering. The problem im facing is, that the data will not appear on the secound view (im doing the same there). I think i have to unsubscribe from the observable, if im leaving the first view or maybe i need to rewrite the data into a separte array. Can anyone please tell me how to share the observable correctly between two views?

Thanks and best regards!


Solution

  • i needed to return the collection from the service and use the valueChanges in the views. Seems like the async pipe now works correctly.

    Best regards