Having an issue with Angular 10 where the behavior of my observable changes based on whether I use a pipe or not. Here are the relevant snippets from my code.
auth.service.ts
...
import { Observable } from 'rxjs';
import { tap } from 'rxjs/operators';
...
register(email: string, password: string): Observable<RegistrationResponse> {
return this.http.post<RegistrationResponse>(
`${environment.API_URL}/users/register`,
{ email, password }).pipe(tap<RegistrationResponse>({
next: (data) => {
console.log('success - tap');
if (data.jwt !== undefined) {
this.setSession(data.jwt);
}
},
error: () => {
console.log('error - tap');
}
})
);
}
...
auth.component.ts
...
this.authService.register(this.email, this.password).subscribe({
next: (_) => {
console.log('success');
this.router.navigate(['/']);
},
error: (error) => {
console.log('error');
this.error = error.error || 'Error';
this.loading = false;
}
});
...
When there is an error response, the expected output is:
error - tap
error
But upon successful request, I get:
success - tap
error <--- unexpected
=> Can anyone explain this behavior and what am I missing?
Additionally, removing the tap pipe results in the completion handler being called as expected.
register(email: string, password: string): Observable<RegistrationResponse> {
return this.http.post<RegistrationResponse>(
`${environment.API_URL}/users/register`,
{ email, password })/*.pipe(tap<RegistrationResponse>({
next: (data) => {
console.log('success - tap');
if (data.jwt !== undefined) {
this.setSession(data.jwt);
}
},
error: () => {
console.log('error - tap');
}
})
);*/
}
Output:
success