Home > Software engineering >  How can I prefill a form with the user's data in this Angular 14 app?
How can I prefill a form with the user's data in this Angular 14 app?

Time:02-02

I am working on an app in Angular 14 that requires authentication/authorization, reason for witch I use Keycloak Angular .

I need to prefill a form with the data of the currently logged in user.

For this purpose, I have a service:

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { User } from '../../../models/user';

@Injectable({
  providedIn: 'root'
})
export class UserFormService {

  httpOptions: object = {
    headers: new HttpHeaders({
      'Content-Type' : 'application/json'
    })
  }

  apiURL: string = 'http://localhost:8080';

  constructor(private http: HttpClient) { }
  
  public currentUserEmail: any;
  public currentUserData: any;

  public getUserByEmail(email: string): Observable<User>{
    return this.http.get<User>(`${this.apiURL}/getUserByEmail/${email}`, this.httpOptions);
  }

}

In the component I do these steps:

Get the user's email:

public currentUserEmail: any;
public currentUserData: any;
public formData: any = {};


public async getUserEmail(){
    let currentUser = await this.keycloakService.loadUserProfile();
    return currentUser.email;
}

And then get the user's data by email:

public async getUserByEmail() {
    this.currentUserEmail = await this.getUserEmail();

    if (this.currentUserEmail) {
      this.formService.getUserByEmail(this.currentUserEmail).subscribe(response => {
        this.currentUserData = response;
        console.log(this.currentUserData);
      });
    } 
}

Attempt to prepopulate the form with the user's data:

public async setFormData() {
    this.formData.first_name = await this.currentUserData.first_name;
    this.formData.last_name = await this.currentUserData.last_name;

    console.log('data: ', this.formData); 
}

With what I want (but fail) to get from the above function, I want to pre-fill the form:

public form: FormGroup = new FormGroup({
    first_name: new FormControl('', Validators.required).setValue(this.formData.first_name),
    last_name: new FormControl('', Validators.required).setValue(this.formData.last_name),
  });

 
 async ngOnInit(): Promise<any> {
    // Get user's email
    this.getUserEmail();
    // Get user's data by email
    this.getUserByEmail();
    await this.setFormData();
}

The problem

The setFormData() method throws the following error:

Uncaught (in promise): TypeError: Cannot read properties of undefined (reading 'first_name')

The same for the rest of the form data.

How do I fix this problem?

CodePudding user response:

You've set up a race condition because await doesn't have any function here. You can't await a class property:

public async setFormData() {
    this.formData.first_name = await this.currentUserData.first_name;
    this.formData.last_name = await this.currentUserData.last_name;

    console.log('data: ', this.formData); 
}

Solution:

public async getUserByEmail() {
    this.currentUserEmail = await this.getUserEmail();

    if (this.currentUserEmail) {
      this.formService.getUserByEmail(this.currentUserEmail).subscribe(response => {
        this.currentUserData = response;
        this.setFormData()
      });
    } 
}

And then change setFormData()

public setFormData() {
    this.formData.first_name = this.currentUserData.first_name;
    this.formData.last_name = this.currentUserData.last_name;
}
  • Related