我有一个名为currentUser的声明变量,它包含一个来自http get请求的用户对象,我只想记录currentUser变量,但我没有定义!有人能解释一下为什么吗?
import { Component, OnInit, NgModule } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { FormGroup, FormControl, FormBuilder, Validators } from '@angular/forms';
@Component({
selector: 'app-profile',
templateUrl: './profile.component.html',
styleUrls: ['./profile.component.css']
})
export class ProfileComponent implements OnInit {
currentUser: any;
user: FormGroup;
cities: any[];
fileToUpload: any;
avatarPath: any;
avatarURL: any;
returnUrl: any;
constructor(
private http: HttpClient,
private fb:FormBuilder
) {
this.createForm();
}
ngOnInit() {
this.http.get('api/user').subscribe(user => {
this.currentUser = user;
localStorage.setItem('currentUser', JSON.stringify(this.currentUser));
});
console.log('this.currentuser :', this.currentUser)
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
});
}发布于 2020-04-01 03:52:36
我认为它的发生是因为同步。试试这个:
this.http.get('api/user').subscribe(user => {
this.currentUser = user;
console.log('this.currentuser :', this.currentUser);
localStorage.setItem('currentUser', JSON.stringify(this.currentUser));
});https://stackoverflow.com/questions/60958482
复制相似问题