Awaiting the asynchronous call in Angular 2 and beyond

Here is a method I am working with:

  prepareCalendarDaysToAdd() {
    this.getDaysToAdd();        //first line
    this.dataSaved.emit(this.daysToAdd); //second line
  }

The getDaysToAdd() method makes an asynchronous call:

getDaysToAdd() {
    this.daysService.getDaysInSpecificYearWith(this.toDate.year).subscribe(
      data => {
        this.getCalendarDaysFrom(data);
      },
      error => { console.error(error); },
      () => {
        this.getCalendarDaysBetween();
      }
    )
  }

The issue here is that the data emits before it's fully prepared. How can I ensure that the async call from the first line is completed before proceeding?

Therefore, the desired code looks like:

  prepareCalendarDaysToAdd() {
    check if getDaysToAdd has finished then emit the list of days
  }

I attempted to use promises to handle this situation, but I seem to be misunderstanding how they should work.

prepareCalendarDaysToAdd() {
     const promise = new Promise((resolve, reject) => {
      this.getDaysToAdd();        //first line
      resolve();
      })
      .then(
      () => {
        this.dataSaved.emit(this.daysToAdd); //second line
        }
      );
    });

Answer №1

Follow the code snippet below to fix your problem :

Insert

this.dataSaved.emit(this.daysToAdd);
within the subscribe function right after this.getCalendarDaysFrom(data); because it is an asynchronous call and emitting data should happen inside its subscription.

prepareCalendarDaysToAdd() {
    this.getDaysToAdd();        //first line
    // removed second line
  }

getDaysToAdd() {
    this.daysService.getDaysInSpecificYearWith(this.toDate.year).subscribe(
      data => {
        this.getCalendarDaysFrom(data);
        this.dataSaved.emit(this.daysToAdd); // Added in success block of subscription
      },
      error => { console.error(error); },
      () => {
        this.getCalendarDaysBetween();
      }
    )
  }

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

Having trouble with installing angular-cli on a Windows 10 system connected to a proxy network

Attempting to setup angular-cli on Windows 10 while connected to a proxy network. Unfortunately, encountering errors when trying to install angular-cli on my machine. Specifically, receiving the following two errors in the command prompt ( 403 Forbidden - ...

Strange appearance of Material UI input field

https://i.stack.imgur.com/az6wt.png Does anyone have an idea why this problem is occurring? When using material UI, the default value and label for the field seem to be overlapping. Below is the code for rendering the fields: {formSchema.map((element, i ...

The error message "The function 'combineLatest' is not found on the Observable type"

Hey there! I'm currently working on implementing an InstantSearch function into my website using Angular 12.2. To accomplish this, I'll be working with a Firestore database with the index "book-data". In my search component, I have included the f ...

Using Typescript and React to retrieve the type of a variable based on its defined type

Just getting started with Typescript and could use some guidance. Currently, I'm using React to develop a table component with the help of this library: Let's say there's a service that retrieves data: const { data, error, loading, refetc ...

Customize stepper background color in Angular Material based on specific conditions

I am working on a project using Angular Material and I want to dynamically change the color of the stepper based on different states. For example: state: OK (should be green) state: REFUSED (should be red) Here is what I have done so far: <mat-horizo ...

Having trouble with ng build optimization error in Angular?

While developing a real-time chat application using Angular 13, I encountered an issue when trying to build the app for testing on my Node.js web server: ng build Every time I run this command, I receive an error in the console. Here is a screenshot of ...

Difficulty recognizing left click on onmouseup and onmousedown events in React with TypeScript

I am experiencing an issue with my code that is meant to update the mousePressed variable accordingly when the mouse button is pressed and released. Surprisingly, it works as expected for right-click and middle-click events but not for left-click. The ev ...

What are the steps for utilizing CzmlDataSource within React Resium?

Currently, I'm attempting to showcase the data from a local czml file on a map using React, Typescript, and Resium. Unfortunately, an error keeps popping up stating "This object was destroyed, i.e., destroy() was called." Can someone point out where m ...

Having trouble getting elastic-apm-node to function with Webpack, Typescript, and ES6?

While working with a TypeScript setup using webpack and babel, I encountered an issue when trying to include elastic-apm-node. Despite having the settings in environment variables, I still faced errors. import * as apm from 'elastic-apm-node/start&ap ...

Encountering a "Error: Uncaught (in promise): EmptyError: no elements in sequence" due to the presence of multiple Angular 9 Route Resolvers

Why do I encounter an error when attempting to use multiple resolvers in Angular routing? If I remove one of the route resolves, everything works fine. But as soon as I include both, the error occurs. https://i.stack.imgur.com/WFI5C.png https://i.stack.im ...

Determining the typing of a function based on a specific type condition

I have created a unique type structure as shown below: type Criteria = 'Criterion A' | 'Criterion B'; type NoCriteria = 'NO CRITERIA'; type Props = { label?: string; required?: boolean; disabled?: boolean; } & ( | ...

Does the a:hover:not() exception only apply to elements with the .active class?

I developed a navigation bar and split it into 3 distinct sections: 1. id="menu" 2. id="fake" (button to fill space) 3. id="social" My main goal is to exclude the .active page and the fake button from the hover effect, but it seems that using a:hover:not( ...

Is there a way to enhance a generic parameter using another generic parameter in TypeScript?

I am struggling with repetitive code that involves a type with minor variations: import { ComponentPropsWithRef, ElementType } from "react"; interface PackshotPropsBase { a: string } interface PackshotPropsWeb { b: string } export type Ele ...

Certain Material-UI components appear to lack proper styling

I found a tutorial on how to incorporate material UI into my app at this link: https://mui.com/material-ui/getting-started However, I noticed that some components are not styled as expected and customizing the theme seems to have no effect... This is how ...

The onNodeContextMenuSelect function does not seem to be functioning properly within the p-tree

<p-tree [value]="files" selectionMode="single" (onNodeContextMenuSelect)="showContect($event)" > </p-tree> Whenever I right click, the event doesn't seem to be triggering. Instead, the default browser c ...

Can a JavaScript object be created in TypeScript?

Looking for a way to utilize an existing JavaScript "class" within an Angular2 component written in TypeScript? The class is currently defined as follows: function Person(name, age) { this.name = name; this.age = age; } Despite the fact that Java ...

Do the circular dependency warnings in Angular pose a significant issue?

Angular has long supported a showCircularDependencies build flag that identifies circular dependencies within classes. But do these warnings pose a real issue? Let's consider an example. import {MyOtherService} from './my-other-service.ts'; ...

Incorporating map, forkJoin, and mergeMap into your code base can

I have a requirement to perform multiple API calls. The first API call returns a list of objects with the properties userId and propertyId. For each item in this list, I need to fetch additional information called userInfo and propertyInfo based on the I ...

The declaration file for the module 'vue-html-to-paper' was not located

Struggling to make a sample project work with HTML to PDF, but encountering an error message stating: Could not find a declaration file for module 'vue-html-to-paper' Even though it resides in my node_modules index.js import Vue from 'vue& ...

Collapse an array containing objects with nested objects inside

Similar questions can be found here and here, but I am struggling to modify the code provided in the answers to fit my specific needs due to its conciseness. The structure of my array of objects is as follows: [ { id: 1, someProp: &quo ...