我正在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.formService.getUserByEmail(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')
表单数据的其余部分也是如此。
1条答案
按热度按时间sgtfey8w1#
你设置了一个争用条件,因为
await
在这里没有任何函数。你不能await
一个类属性:解决方案:
然后更改
setFormData()