【问题标题】:How can I prefill a form with the user's data in this Angular 14 app?如何在此 Angular 14 应用程序中使用用户数据预填充表单?
【发布时间】:2023-02-01 00:41:30
【问题描述】:

我正在 Angular 14 中开发一个需要身份验证/授权的应用程序,这是我使用女巫的原因Keycloak Angular .

我需要用当前登录用户的数据预填表格。

为此,我有一项服务:

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

}

在组件中,我执行以下步骤:

获取用户的邮箱:

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


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

然后得到通过电子邮件的用户数据:

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

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

尝试使用用户数据预填充表单:

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

有了我想要(但失败)从上述功能中得到的东西,我想预先填写表格:

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

问题

setFormData() 方法抛出以下错误:

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

其余的表单数据也是如此。

我该如何解决这个问题?

【问题讨论】:

    标签: javascript angular angularjs angular14


    【解决方案1】:

    问题是 setFormData 方法在从 API 调用加载之前试图访问 this.currentUserData。由于 API 调用是异步的,您需要等待响应到达,然后再尝试访问数据。

    您可以通过将 setFormData 方法移到 getUserByEmail 方法中来解决此问题:

    public async getUserByEmail() {
      this.currentUserEmail = await this.getUserEmail();
    
      if (this.currentUserEmail) {
        this.supplierFormService.getPartnerByEmail(this.currentUserEmail).subscribe(response => {
          this.currentUserData = response;
          console.log(this.currentUserData);
          this.setFormData();
        });
      } 
    }
    

    或者您可以将 async/await 与 subscribe 方法一起使用:

    public async getUserByEmail() {
      this.currentUserEmail = await this.getUserEmail();
    
      if (this.currentUserEmail) {
        await this.supplierFormService.getPartnerByEmail(this.currentUserEmail)
          .toPromise()
          .then(response => {
            this.currentUserData = response;
            console.log(this.currentUserData);
            this.setFormData();
          });
      } 
    }
    

    【讨论】:

      猜你喜欢
      • 2017-06-25
      • 1970-01-01
      • 2019-10-30
      • 2014-05-29
      • 1970-01-01
      • 2019-01-29
      • 1970-01-01
      • 1970-01-01
      • 2022-01-24
      相关资源
      最近更新 更多