【发布时间】: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