I recently started learning RxJS and am currently focusing on observables and subjects. I have a basic login code that is split into two separate files: a) auth.service.ts and b) login.component.ts
Below is the content of login.component.ts:
public login(username: string, password: string): Observable<boolean> {
const headers = { 'content-type': 'application/json' }
const reqBody = {
"userName": username,
"password": password
};
const body = JSON.stringify(reqBody);
const subject = new Subject<boolean>();
this.httpClient.post<IAuthToken>(this.apiUrl, body, { 'headers': headers })
.subscribe(response => {
if (response) {
localStorage.setItem(this.accessTokenKey, response.access_token);
subject.next(true);
}
else {
throwError("Login request failed. Please try again later");
}
},
error => {
// TODO : Code to show invalid username password
// this code throws error. Subscribe in the login.component.ts doesnt receive any error.
throwError(error.error);
});
return subject.asObservable();
}
And here is the code for the login.component.ts:
errorMsg: string;
constructor(
private authenticationService: AuthService
) { }
async onLogin(): Promise<void> {
this.authenticationService.login(this.loginForm.value.username,
this.loginForm.value.password)
.subscribe((response) => {
this.errorMsg = null;
if (response)
console.log("logged In");
},
error => {
// TODO : Code to show invalid username password
// This code doesnt execute, i.e. error is not caught.
this.errorMsg = error.error;
console.log(error);
});
}
}
I am trying to throw an error for an invalid username or password from auth.service.ts and catch it in login.component.ts so that I can display the error message on the UI. However, when I use throwError in auth.service.ts, the error is not being caught in login.component.html.