【发布时间】:2019-02-28 02:58:14
【问题描述】:
我有两种方法:返回用户配置文件的 getUserProfile 和更新用户数据的 updateProfile。
UpdateProfile 方法可以正常工作,因为它在数据库中显示有效的更新数据。我的getUserProfile 方法有问题,因为调用updateProfile 方法后组件中的更新数据没有显示,而是显示更改之前的数据Data not updated correctly。只有当我退出应用程序并再次登录时它才会显示更新的数据。
我认为问题在于 localstorage 和 userToken 值,因为它在注销后被清除。并且只有在重新登录后才会再次调用 getUserProfile 方法并正常工作。Changed data in database after calling updateProfile
组件类:
export class AccountComponent implements OnInit {
userData: any;
profileForm: FormGroup;
constructor(private formBuilder: FormBuilder, private authenticationService: AuthenticationService, private router: Router) { }
ngOnInit() {
this.formInitBuilder();
this.authenticationService.getUserProfile().subscribe( (data: any) => {
this.userData = data;
this.profileForm.setValue({
username: data.UserName,
email: data.Email,
firstName: data.FirstName,
lastName: data.LastName
});
console.log(data);
});
}
formInitBuilder() {
this.profileForm = this.formBuilder.group ({
username: [ '' ],
email: [ '' ],
firstName: [ '' ],
lastName: [ '']
});
}
onSubmit(registrationForm: FormGroup) {
if (registrationForm.valid) {
this.authenticationService.updateProfile(this.profileForm.value).
subscribe(() => {
this.router.navigate(['/home']);
});
}
}
}
服务类:
getUserProfile() {
return this.http.get(this.rootUrl + '/api/GetUserClaims',
{headers: new HttpHeaders({'Authorization': 'Bearer ' + JSON.parse(localStorage.getItem('userToken'))})});
}
updateProfile(userData) {
const profile = {
Username: userData.username,
Email: userData.email,
FirstName: userData.firstName,
LastName: userData.lastName,
};
const reqHeader = new HttpHeaders({'Content-Type': 'application/json'});
return this.http.post(this.rootUrl + '/api/ChangeProfile', profile, {headers: reqHeader});
}
网络接口:
[HttpGet]
[Route("api/GetUserClaims")]
public AccountModel GetUserClaims()
{
var identityClaims = (ClaimsIdentity)User.Identity;
IEnumerable<Claim> claims = identityClaims.Claims;
AccountModel model = new AccountModel()
{
UserName = identityClaims.FindFirst("Username").Value,
Email = identityClaims.FindFirst("Email").Value,
FirstName = identityClaims.FindFirst("FirstName").Value,
LastName = identityClaims.FindFirst("LastName").Value,
LoggedOn = identityClaims.FindFirst("LoggedOn").Value
};
return model;
}
【问题讨论】:
-
你的问题有太多的移动部件,也没有明确的minimal reproducible example。请重构它并找出您需要帮助的问题。
标签: angular