Execute a function following the subscription's finalization

I have data stored in a Firebase Realtime Database that I want to display in my Angular application upon startup. My TripService is responsible for loading the data, and I am facing an issue with passing this data to the main AppComponent. I attempted to convert the subscription to a Promise, but it did not work as expected. Can you help me identify where I am going wrong? Additionally, how can I ensure that AppComponent reads the data only after TripService has loaded it?

The crucial code snippet from trip.service.ts is shown below:

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;})
  }
}

The key part of app.component.ts looks like this:

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

Answer №1

A straightforward solution is to utilize the Observable component.

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()}))))
  }
}

In your app component, you can do the following:

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

This approach involves returning an observable and subscribing to it within your component.

Answer №2

It seems like there was an error in converting it to a promise. The correct way to do it would be to add take(1) to limit it to only one event before completing the promise.

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The Webstorm AngularJS extension appears to be malfunctioning, as it is not able to recognize the keyword 'angular'

As a beginner in Angularjs and web development, I have been using Webstorm to develop my projects. I have already installed the Angularjs plugin, which seems to be working fine in my HTML files. However, I am facing an issue with my .js file. In this file, ...

Fetching data in VueJs before redirecting to a new page

Within the mounted function, I am creating an action that fetches data from a Rest API and populates my table in a Vue.js component mounted() { UserService.getProjects().then( (response) => { this.isProject = true; this.project ...

Connecting an AngularJS directive to a controller

I'm in the process of learning AngularJS directives and facing a challenge. Here's the JSFiddle link to an example I'm working on: https://jsfiddle.net/7smor9o4/ In the example, my expectation is for the vm.alsoId variable to match the valu ...

express.js and socket.io compatibility perplexity

Server-Side Code: var server = require("http").Server(express); var io = require("socket.io")(server); server.listen(5000); io.on('connection', function(client) { client.on('order', function(data) { io.emit('place_orde ...

Add data to form by clicking on the map using Mapbox

When using mapbox, I am able to insert a marker on map click and want to append those values in a form so that I can use my controller to store them. The marker is added and values are appended; however, https://i.sstatic.net/Tv1lk.jpg In the last value ...

Issue with *ngFor not running when utilizing a module variable in an ionic/angular application

Currently, I am working on an Ionic/Angular application where I encountered an issue with displaying values from a list using *ngFor within a statement. It seems that *ngFor is not functioning properly for some reason. When I use *ngFor="let i of eventLis ...

Can someone explain the method for displaying or concealing a menu based on scrolling direction?

https://i.stack.imgur.com/tpDx0.jpg I want to hide this menu when scrolling down and show it when scrolling up. The code for my menu bot is: <script> var previousScroll = 0; $(window).scroll(function(event){ v ...

Having difficulty scrolling down in a section with 100% height on iOS devices

Currently facing an issue with a website I am creating for my wedding invitation. The top section is set to have a 100% height and requires scrolling to view the rest of the content. While it functions perfectly on FireFox / Chrome on my computer, there s ...

Using a local function within Node.js and referencing it with the <%%> tag in a document

I am currently working with Node.js and attempting to utilize a local function within a document that requires the JSON I send in the res.render. Is there a method to achieve this? Below is an example of how I attempted to implement it: <%local_vari ...

Angular is not providing the anticipated outcome

I'm new to Angular (7) and I'm encountering an issue while trying to retrieve the status code from an HTTP request. Here's the code snippet used in a service : checkIfSymbolExists() { return this.http.get(this.url, { observe: 'res ...

Running PHP scripts within an Angular2 CLI application

I'm currently working on an Angular 2 app using Angular CLI, but I've noticed that the PHP files are not being compiled correctly. I'm curious if the server that is included with Angular CLI supports PHP. If not, do you have any recommendati ...

Is there a way to display incoming chat messages on the chat box without requiring a page refresh using socket.io?

Having trouble resolving an issue with my application hosted on wpengine, built using WordPress, vue.js, and socket.io for chat functionality. The main concern is that new messages posted in the chatbox do not display until the page is refreshed. I'm ...

The prototype's function doesn't pause for anything, carrying out its duty in a continuous cycle

I have been attempting to enhance the prototype of an object by adding an asynchronous function to be called later on. Here is my approach: const ContractObject = Object; ContractObject.prototype['getBalance'] = async function(userId: number ...

retrieve the coordinates of the northwest and southeast corners of a group of markers displayed on a Google Map

Is there a more efficient way to get the NE and SW corners of a set of markers on a Google map without iterating over each marker individually using JavaScript or Google functions? function fnSetBounds(){ var lowLat = 90; var highLat ...

Bootstrap Django Table Paginating

Having some difficulty implementing table pagination in a django-bootstrap project. The bootstrap's table pagination feature is not displaying on my template as expected. I am using one of the default bootstrap tables with custom styles, and seeking a ...

Cycle through an array an unlimited number of times using a combination of forEach and setTimeout

In my myClass, I am facing an issue with the method. When it reaches the end of the array, instead of starting over from 0, it simply stops. this.jsonParse = function() { for (var i = 0; i < this.numberOfPhotos; i++){ (function(index, sele ...

Gathering user key event input for a duration of 2 seconds before resetting it

I need help implementing a feature where I can clear the user's input text after 500ms if they are entering characters consecutively. private userInputTimer; private userInputText = ''; private handleEvent(event: KeyboardEvent): void { if ...

Start up a server-side JavaScript instance utilizing Express

My journey into web programming has led me to learning JavaScript, Node.js, and Express.js. My ultimate goal is to execute a server-side JavaScript function (specifically a function that searches for something in a MySQL database) when a button is pressed ...

jQuery carousel displaying a blank slide at the conclusion

I am experiencing an issue with my slideshow where it shows an empty slide after the last element. I suspect that there is something in my script causing this behavior, as it seems to be finding one extra child for the element and adding it as an empty spa ...

Ways to invoke jQuery(this) within an anchor tag's onclick event handler

My task involves working with HTML code and I need to apply a class name to the parent li tag using jQuery. Here is the HTML code snippet: <ul> <li><a onclick="setSelectedTestPlan();" href="javascript:void(0);">New Test</ ...