One function must pause and await the outcome of another function

I am developing a form that utilizes the data of the currently logged in user. The function responsible for setting the value of the form is executed before retrieving the user data.

ngOnInit() {
    this.auth.getUserState()
      .subscribe( user => {
        this.user = user;
      });
    this.resetForm();
  }

  resetForm(form?: NgForm) {
    if (form != null) { form.resetForm(); }
    this.service.formData = {
      who: this.user.email,
      id: null,
      name: '',
      content: '',
      date: null,
      done: false
    };
  }

Is there a way to prevent "resetForm" from initializing before the component retrieves the current user data and properly populates the "who" field?

Answer №1

To ensure that the resetForm() is only called when the user information is available, you can include it inside the subscription of getUserState():

ngOnInit() {
    this.auth.getUserState()
      .subscribe( user => {
        this.user = user;
        this.resetForm();
      });      
  }

This way, the resetForm(...) function will be executed only when the user information has been retrieved.

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 importing a feature module in Angular 6? It seems that function calls are not allowed in the decorators causing the

I am a newcomer to Angular 6, transitioning from AngularJS 1.x. Currently, I am facing an issue while trying to import a custom module into my main application. It seems to be an error related to AOT compiling in Angular, which I am struggling to understan ...

Having trouble rendering Next.JS dynamic pages using router.push()? Find out how to fix routing issues in your

The issue I am facing revolves around the visibility of the navbar component when using route.push(). It appears that the navbar is not showing up on the page, while the rest of the content including the footer is displayed. My goal is to navigate to a dy ...

When performing the operation number.tofixed in Typescript, it will always return a string value instead of a double datatype as expected from parseFloat

let value = 100 value.toFixed(2) -> "100.00" parseFloat(value.toFixed(2)) -> 100 I am encountering an unexpected result with the double type when input is 100.36, but not with 100.00. Framework: loopback4 ...

What is the best way to simulate a service HTTP request using Jasmine in an Angular application?

Why is my spy not working as expected? I've set up a spy for the prescriptionService and am monitoring the fetchClientPrescriptions method, but when I try to verify if it has been called, I encounter an error. However, the spy for getClientPrescriptio ...

Need help with TypeScript syntax for concatenating strings?

Can you explain the functionality of this TypeScript syntax? export interface Config { readonly name: string readonly buildPath: (data?: Data) => string readonly group: string } export interface Data { id: number account: string group: 'a&a ...

`Using ng-select in Angular to showcase specific bindLabel and bindValue`

In my Angular-15 project, I am working with a list of countries that includes both country codes and names: component.ts: export class AppComponent { out = new EventEmitter(); constructor() {} countries = [ { code: 1, name: 'Ukrain' }, ...

Looking up the Vue.js type definitions in TypeScript

I'm currently working on enabling type checking in my Vue.js code (v2.2.1). My initial goal is to ensure that this specific line compiles with TypeScript (meaning I want the Vue class to be properly identified): var app = new Vue(); I've discov ...

Encountering difficulties while trying to install ng2-material in Angular 2

I'm attempting to utilize a data table with the ng2-material library from ng2-material as shown below: <md-data-table [selectable]="true"> <thead> <tr md-data-table-header-selectable-row> <th class="md-text-cell">M ...

Is TypeScript React.SFC encountering incompatibility issues with types?

Trying to figure out TypeScript but struggling to get rid of these persistent errors. I've tried multiple approaches and resorted to using any wherever possible, but the errors still persist: (9,7): Type '(props: IRendererProps & { children? ...

Angular's custom reactive form validator fails to function as intended

Struggling to incorporate a customized angular validator to check for date ranges. The validator is functioning correctly and throwing a validation error. However, the issue lies in the fact that nothing is being displayed on the client side - there are n ...

Using multiple MaterialUI components in a JavaScript page with React can pose challenges

Incorporating multiple MaterialUI Cards in my project, I encountered an issue where all the cards would expand or the select values would change simultaneously. Despite using unique key values and mapped components with distinct keys, the problem persisted ...

The alertController will only appear on the original page where it was first activated

I am facing a peculiar issue with the alertController in my Ionic application. Let me explain the problem and then provide the relevant code snippets. In my Ionic app with tabs, I encounter an issue where alerts are not showing up correctly. For example, ...

"Discover a new approach to incorporating the ChangeDetectorRef service into your pipe functions

I am facing an issue while trying to inject the ChangeDetectorRef service into my custom pipe in Angular. The error I am encountering is: No provider for ChangeDetectorRef! Although I have looked at various examples related to similar functionalities (suc ...

Utilize Charts.js to transform negative values into graphical representations

I am struggling with transforming the expense data into a positive number in my bar chart. The data consists of both income and expenses, and I want to display them as positive numbers for easier comparison. I attempted using Math.abs(this.barData[1]) in n ...

Encountering Compilation Error in @microsoft/mgt Graph Toolkit Upon Transition from Angular 11 to Angular 13

Previously, I had integrated the Microsoft toolkit into my Angular 11 application without any issues. However, when I was asked to upgrade to Angular 13 and updated the toolkit to its latest version (2.3.2 at the time of writing), I started encountering co ...

Error: The function call does not match any of the overloads. 'VueRouter' is not recognized

I'm new to TypeScript and currently trying to implement vue-router in my project. Encountering the following errors: Error TS2769: No overload matches this call in source\app\main.ts(3,3). Overload 1 of 3, '(options?: ThisTypedCompon ...

How to remove the border of the MUI Select Component in React JS after it has been clicked on

I am struggling to find the proper CSS code to remove the blue border from Select in MUI after clicking on it. Even though I managed to remove the default border, the blue one still persists as shown in this sandbox example (https://codesandbox.io/s/autumn ...

The attribute 'y' is not found within the data type 'number'

Currently working on a project using Vue.js, Quasar, and TypeScript. However, encountering errors that state the following: Property 'y' does not exist on type 'number | { x: number[]; y: number[]; }'. Property 'y' does not ...

Is there compatibility between Ionic and Kindle Fire/Galaxy Tab devices?

Are there specific challenges when developing in Ionic for Kindle Fire and Galaxy Tab devices? Do the code/assemblies and target Framework differ from other Android devices? ...

Retrieving attributes by their names using dots in HTML

Currently working on an Angular 2 website, I am faced with the challenge of displaying data from an object retrieved from the backend. The structure of the object is as follows: { version: 3.0.0, gauges:{ jvm.memory.total.used:{ value: 3546546 }}} The is ...