I've created an app with user authentication system. Firstly I check if user with given registration e-mail exists and if does not - I call registration service.
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();
}
The user is registered properly, but the marked code is not executed. In AuthService - {observe: 'response'} is added to both get (findUser) and post (registerUser) requests.
You should not subscribe to the inner observable, correct approach is to combine observables to just one and subscribe to it:
Note that I also simplified your code, no need for
tap
andconcatMap
. Other thing was that condition forfound
and!found
- the thirdelse
branch could never be executed so I removed that as well.https://www.learnrxjs.io/operators/transformation/mergemap.html