Service call delay not displayed on screen

I have a function that I execute in my component's ngOnInit lifecycle hook. This function calls a service to fetch data and populate an array. Once that array is filled, I then call another service method using the data from the first array to populate a second array.

The issue I'm facing is that when the page renders, the second array appears to still be empty, resulting in nothing being displayed on the screen.

Below is a simplified example of my code:

changedBookings: Booking[] = [];
currentBookings: Booking[] = [];

constructor(private bookingService: BookingService) { }

  ngOnInit() {

    //Retrieve all changes and apply filters
    this.bookingService.getAllHistory()
        .subscribe(
            data => {
                this.changedBookings = (data as any).results
            },
            err => {
                console.log(err);
            },
            () => {
                this.getCurrentBookings();
            })
  }

  getCurrentBookings() {
      for(let i of this.changedBookings) {
          this.bookingService.getRoomBooking(i.date,i.level,i.room)
              .subscribe(
                  data => this.currentBookings.push((data as any).results),
                  err => console.log(err),
                  () => {
                    //The console logs show data being added to the array
                    console.log(this.currentBookings);
                  }
              )
      }
  }
<div class="row">

  <div *ngFor="let booking of changedBookings">
    {{booking.date}}
  </div>

  <!--This section doesn't display anything-->
  <div *ngFor="let booking of currentBookings">
    {{booking.date}}
  </div>
  
</div>

I am looking for a solution that allows me to successfully use both arrays in my HTML template.

Answer №1

Simple solution at the end. However, it's possible for someone else to encounter this issue.

getCurrentBookings() {
  for(let i of this.changedBookings) {
      this.bookingService.getRoomBooking(i.date,i.level,i.room)
          .subscribe(
              data => this.currentBookings.push((data as any).results),
              err => console.log(err),
              () => {
                //displaying the filled array
                console.log(this.currentBookings);
              }
          )
  }

}

While looping through this, an array of objects was being pushed at each iteration, resulting in something like this:

[ [{}],[{}] ]

This, of course,

<div *ngFor="let booking of currentBookings">
  {{booking.date}}
</div>

Would be undefined. The quick fix without modifying any other code is as follows:

<div *ngFor="let booking of currentBookings">
  {{booking[0].date}}
</div>

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

Prohibit the Use of Indexable Types in TypeScript

I have been trying to locate a tslint rule in the tslint.yml file that can identify and flag any usage of Indexable Types (such as { [key: string] : string }) in favor of TypeScript Records (e.g. Record<string, string>). However, I haven't had a ...

Angular's DecimalPipe will truncate any strings that exceed 10 digits

Using the decimal pipe to format numbers in an input field value| number:'0.0-6': 'en-us' When working with numbers containing more than 10 digits, it displays as follows: For 11111111111.123456, it formats to 11,111,111,111.123455 ...

What is the reason behind receiving the error message "Unable to resolve all parameters for ApplicationModule"?

I am experiencing an issue with my Angular app as it is not working properly in CodeSandbox. The error message I receive is: Can't resolve all parameters for ApplicationModule evaluate main.ts:11:25 8 | enableProdMode(); 9 | } 1 ...

Tips for refreshing the service page in Ionic 2

One of my services is called "user-data", and its main function is to fetch "user data" when a request is received. I have a specific page that is responsible for displaying this "user data". Upon loading the page, it retrieves the data and displays it. ...

Facing an issue with ngx quill editor malfunctioning when utilizing the cdkDrag directive from Angular Material

Having trouble with the focus on the Quill editor or typing content while using the cdkDrag directive from Angular Material. Check out my code on StackBlitz: https://stackblitz.com/edit/angular-ivy-xalouc Issue Summary: The editor is only editable when ...

Learn how to efficiently disable or enable a button in Angular depending on the selected radio button

In order to disable the button when the remarks are marked as failed. Here is an example scenario: Imagine there is an array containing two to four items. First example: ITEM 1 -> FAILED -> Remarks (required) ITEM 2 -> FAILED -> Remarks (r ...

What causes a folder to disappear after rerunning in nest.js?

When working on my project using nest.js in MacOS Sonoma, I encountered a problem where the image folder src/products/images gets deleted after every project rerun (npm start). The images are saved like this: for (const image of images) { const fileName ...

What is the process for obtaining the result of an asynchronous function triggered by an event in HTML?

I am currently working on an Angular application where I have a button that triggers a click event. The method being called is asynchronous and involves subscribing to an observable. My goal is to call player.start() only after the listItems.getData() meth ...

When compiling in Visual Studio 2019, the process terminated with exit code -1073741819

Today, upon returning to my asp .net core-project with react and typescript as front end, I encountered an error message after running the "Build" command. Can anyone shed some light on what this error means and how it can be fixed? Severity Code De ...

How can you update ngModel in Angular and mark the form as dirty or invalid programmatically?

My form is connected to a model as shown below In the component file: myTextModel: string; updateMyTextModel(): void { this.myTextModel = "updated model value"; //todo- set form dirty (or invalid or touched) here } Html template: <form #test ...

The statement "import React from 'react'" is automatically removed by VS Code

When I need to remove unused modules that I no longer need, I frequently use shift + alt + o. This method has worked perfectly for me in the past when editing .tsx files. However, recently, VS Code seems to be removing the import React from 'react&ap ...

Transferring information between components within AngularJS

export class AppComponent { title = 'shopping-cart'; ngOnInit() { } images = [ { title: 'At the beach', url: 'https://images.unsplash.com/photo-1507525428034-b723cf961d3e?ixlib=rb-4.0.3&ixid=MnwxMjA ...

Investigating TypeScript Bugs in Visual Studio Code

As I navigate through various sources, I notice that there is a plethora of information available on older versions of VSCode (v1.16.1 - the most recent version at the time of writing) or deprecated attributes in the launch.json file. I have experimented ...

Activate the download upon clicking in Angular 2

One situation is the following where an icon has a click event <md-list-item *ngFor="let history of exportHistory"> <md-icon (click)="onDownloadClick(history)" md-list-avatar>file_download</md-icon> <a md-line> ...

Activate the field once the input for the other field is completed

I have a form where the last name field is initially disabled. How can I make it so that the last name field becomes enabled only when the first name is inputted? <form> <label for="fname">First name:</label><br> ...

Angular request accessing CoinMarketCap API

Currently, I am immersing myself in the world of the latest CoinMarketCap API and navigating through the waters of data. The Node.js example below demonstrates how to make a request. But how can I achieve the same in Angular? Any tips or suggestions would ...

Tips for stopping TypeScript code blocks from being compiled by the Angular AOT Webpack plugin

Is there a way to exclude specific code from Angular's AOT compiler? For instance, the webpack-strip-block loader can be utilized to eliminate code between comments during production. export class SomeComponent implements OnInit { ngOnInit() { ...

Troubleshooting: Issues with CORS in Django and Angular for POST requests

My Angular4 application (currently running on http://127.0.0.1:4200 development server) needs to communicate with a Django REST backend on the web. The backend is hosted on HTTPS (via Apache server directing requests to a gunicorn server on an internal por ...

Obtain an array of column values within an array of objects using Angular 12

I am working on an Angular 12 project and need to fetch all data from the artisticBehaviour column in the Users table, excluding NULL values or duplicates e.g. Actor, Actor. Below is the TypeScript function that retrieves all users from the Users table. a ...

What is the technique for accessing the original function within a class using a proxy?

I attempted to monkey patch a function within my class using Proxy. Is there a way to access and execute the original function? class foo { x = 10; bar() { console.log({ x: this.x }); } } foo.prototype.bar = new Proxy(foo.prototype.bar, { ap ...