我已经使用用户身份验证系统创建了一个应用。首先,我检查具有给定注册电子邮件的用户是否存在-不存在-我致电注册服务。
register.component.ts
registerUser(email: String, password: String) {
let found = false;
this.authService.findUser(email).pipe(
tap(res => { console.log(res.status);
if (res.status === 202) { found = true; } else if (res.status === 200) { found = false; } else {found = null; }}),
concatMap(res => {
console.log(found);
if (found) {
this.snackBar.open('E-mail already taken.', 'Ok', { duration: 3000 });
} else if (!found) {
this.authService.registerUser(email, password).subscribe(res2 => {
/* CODE DOES NOT EXECUTE - START */
console.log(res2.status);
if (res2.status === 201) {
this.router.navigate(['/list']);
} else {
this.snackBar.open('Unable to add new user.', 'Try later', { duration: 3000 });
}
/* CODE DOES NOT EXECUTE - END*/
});
} else {
this.snackBar.open('Checking e-mail address failed.', 'Try later', { duration: 3000 });
}
return of(res);
})
).subscribe();
}
用户已正确注册,但未执行标记的代码。 在AuthService中-{get:'response'}已添加到get(findUser)和post(registerUser)请求中。
答案 0 :(得分:1)
您不应订阅内部的可观察对象,正确的方法是将可观察对象仅合并为一个并对其进行订阅:
registerUser(email: String, password: String) {
this.authService.findUser(email)
.pipe(
flatMap(res => {
let found = null;
if (res.status === 202) {
found = true;
} else if (res.status === 200) {
found = false;
}
console.log(found);
if (found) {
this.snackBar.open('E-mail already taken.', 'Ok', { duration: 3000 });
return of(res);
}
return this.authService.registerUser(email, password);
}),
)
.subscribe(res2 => {
console.log(res2.status);
if (res2.status === 201) {
this.router.navigate(['/list']);
} else {
this.snackBar.open('Unable to add new user.', 'Try later', { duration: 3000 });
}
});
}
请注意,我还简化了您的代码,不需要tap
和concatMap
。另一件事是found
和!found
的条件-永远无法执行第三个else
分支,因此我也将其删除。
https://www.learnrxjs.io/operators/transformation/mergemap.html