В моем методе ngOnInit я вызываю свой api, чтобы получить информацию о пользователе и установить ее в переменную currentUser, при попытке исправить содержимое currentUser в группу from, которую я получил:
this.currentUser is undefined
. ts файл
export class ProfileComponent implements OnInit {
currentUser: any;
user: FormGroup;
firstName: any;
lastName: any;
cities: any[];
fileToUpload: any;
avatarPath: any;
avatarURL: any;
returnUrl: any;
counts: any;
constructor(
private http: HttpClient,
private router: Router,
private toastr: ToastrService,
private route: ActivatedRoute,
private fb: FormBuilder
) {
this.createForm();
}
createForm() {
this.user = this.fb.group({
firstName: new FormControl('', [Validators.required, Validators.minLength(3), Validators.pattern('^[a-zA-Z \-\']+')]),
lastName: new FormControl('', [Validators.required, Validators.minLength(3), Validators.pattern('^[a-zA-Z \-\']+')]),
email: new FormControl('', [Validators.email]),
gender: new FormControl('', [Validators.required]),
birthDate: new FormControl(''),
phone: new FormControl({ value: '', disabled: true }, [Validators.required]),
oldPassword: new FormControl(''),
password: new FormControl(''),
profession: new FormControl('', [Validators.pattern('^[a-zA-Z \-\']+')]),
address: new FormControl('', [Validators.required]),
city: new FormControl({ value: '', disabled: true }),
postalCode: new FormControl('', [Validators.required, Validators.min(1000), Validators.max(10000)])
}, )
}
ngOnInit() {
this.http.get('api/user').subscribe(user => {
this.currentUser = user;
localStorage.removeItem('currentUser');
localStorage.setItem('currentUser', JSON.stringify(this.currentUser));
});
this.returnUrl = this.route.snapshot.queryParams['returnUrl'] || '/';
this.http.get('api/cities').subscribe((cities: any[]) => {
this.cities = cities;
});
this.user.patchValue({
firstName: this.currentUser.firstName,
lastName: this.currentUser.lastName,
email: this.currentUser.email,
profession: this.currentUser.profession,
gender: this.currentUser.gender,
birthDate: this.currentUser.birthDate,
phone: this.currentUser.phone,
oldPassword: this.currentUser.oldPassword,
password: this.currentUser.newPassword,
address: this.currentUser.address,
postalCode: this.currentUser.postalCode,
city: this.currentUser.city._id
});
}
}
как это исправить и исправить содержимое моей переменной в пользовательской formGroup? даже когда я пытаюсь зарегистрировать содержимое currentUser вне http, получаю его undefined!