Search code examples
javascriptangulartypescriptfirebasees6-promise

Run a function after subscription is complete


I have some data stored in a Firebase Realtime Database. I want my Angular application to load and show it when it starts. I have a TripService that loads data and a main AppComponent. In a TripService, I retrive the data using subscribe() method. However, I am having trouble sending this data to AppComponent. I tried converting this subscription to a Promise, but my solution doesn't work. Could you tell me what mistake am I making? Also, how do I make sure that AppComponent reads data after TripService loads it?

This is the most important code in trip.service.ts

export class TripService {
  trips: any;
  private db: AngularFireDatabase
  constructor(database: AngularFireDatabase) {
      this.db = database;
  }

  async loadAllTrips(){
    this.db.list('trips').snapshotChanges()
    .pipe(map(changes =>
      changes.map(c =>
        ({key: c.key, ...<Object>c.payload.val()}))))
    .subscribe(data => {
      this.trips = data;})
  }
}

This is the most important code in app.component.ts

export class AppComponent implements OnInit {
  ngOnInit() {
    this.tripService.loadAllTrips()
      .then(() => {this.trips = this.tripService.trips;);
  }
  trips: any;
}

Solution

  • Simple solution is to use Observale

    export class TripService {
      trips: any;
      private db: AngularFireDatabase
      constructor(database: AngularFireDatabase) {
          this.db = database;
      }
    
      loadAllTrips(){
        return this.db.list('trips').snapshotChanges()
        .pipe(map(changes =>
          changes.map(c =>
            ({key: c.key, ...<Object>c.payload.val()}))))
      }
    }
    

    and in you app component

    export class AppComponent implements OnInit {
      ngOnInit() {
        this.tripService.loadAllTrips()
          .subscribe(trips => this.trips = trips);
      }
      trips: any;
    }
    

    You simply return an observable and subscribe to it in your component