gpt4 book ai didi

javascript - Angular数据同步问题

转载 作者:行者123 更新时间:2023-12-02 21:17:49 26 4
gpt4 key购买 nike

如果输入中的某些电子邮件地址已存在,我想从后端检索信息。根据这些信息,我调用一个函数来发布将用户插入数据库的帖子。问题是只有在第二次单击“注册”按钮后才会插入用户(在此按钮上调用函数 registerUser)。

组件内容:

 registerUser(form: NgForm) {
let date: Date = new Date();
this.newUser.registrationDate = date;
this.checkEmailStatus(); //IMPLEMENTATION BELOW
if (this.signupForm.valid === true && this.emailStatus) {
this.portfolioAppService.registerUser(this.newUser).subscribe((data) => {
this.clearFields();
this.navigateToLogin();
},
error => console.error(error)
);
}
}

checkEmailStatus() {
this.portfolioAppService.checkEmailStatus(this.newUser.email).subscribe((data: string) => {
if (data != "") {
this.emailStatus = true;
}
else this.emailStatus = false;
},
error => console.error(error)
);
}

这是我的服务:

  checkEmailStatus(email: string): Observable<string> {
return this.http.get<string>(`/api/Users/CheckEmailStatus_${email}`, this.httpOptions);
}

这是后端:

    [HttpGet]
[Route("~/api/Users/CheckEmailStatus_{email}")]
public string CheckEmailStatus(string email)
{
try
{
User user = _context.Users.Where(u => u.Email == email).FirstOrDefault();
if (user != null)
{
return user.Email;
}
else
{
return "";
}

}
catch (Exception e)
{
throw new Exception("Error!");
}

}

最佳答案

this.portfolioAppService.checkEmailStatus() 的调用是 asynchronous 。因此,当您在 this.checkEmailStatus() 调用后检查 if (this.signupForm.valid === true && this.emailStatus) 时,变量 this. emailStatus 仍未定义。要修复此问题,您可以从组件中的 checkEmailStatus() 返回一个可观察值。尝试以下方法

组件

registerUser(form: NgForm) {
let date: Date = new Date();
this.newUser.registrationDate = date;
this.checkEmailStatus().pipe(take(1)).subscribe(status => {
if (this.signupForm.valid === true && status) { // <-- check the status of email address
this.portfolioAppService.registerUser(this.newUser).subscribe((data) => {
this.clearFields();
this.navigateToLogin();
},
error => console.error(error)
);
}
});
}

checkEmailStatus() : Observable<boolean> {
const result = new Subject<boolean>();

this.portfolioAppService.checkEmailStatus(this.newUser.email).subscribe(
(data: string) => {
if (data !== '') {
result.next(true);
}
else result.next(false);
},
error => {
console.error(error);
result.next(false);
}
);

return result.asObservable();
}

关于javascript - Angular数据同步问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60920728/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com