I'm building an angular app with a login/registration flow, and ATM I'm looking for an easy and more readable way to code the following:
register() {
this.accountService.register(this.user, this.password, this.passwordConfirmation).subscribe(() => {
this.accountService.login(this.user.email, this.password).subscribe((loginResult) => {
this.accountService.csrfRefresh().subscribe(() => {
if (loginResult.status === ELoginStatus.success) {
this.router.navigateByUrl(this.returnUrl);
} else {
this.errorMessage$.next('Login unsuccessful');
}
}, () => {
this.errorMessage$.next('Login unsuccessful');
})
}, () => {
this.errorMessage$.next('Login unsuccessful');
})
}, () => {
this.errorMessage$.next('Login unsuccessful');
});
}
With this code I need to write the error handling code 4 times, or create a seperate method, or pass data on to a BehaviorSubject
. This seems to be sluggish.
Something I've been considering is to use await
:
async register() {
try {
await this.accountService.register(this.user, this.password, this.passwordConfirmation).toPromise();
const loginResult = await this.accountService.login(this.user.email, this.password).toPromise();
await this.accountService.csrfRefresh().toPromise();
// TS2532: Object is possibly 'undefined'
if (loginResult!.status === ELoginStatus.success) {
this.router.navigateByUrl(this.returnUrl);
} else {
this.errorMessage$.next('Login unsuccessful');
}
} catch (exception) {
this.errorMessage$.next('Login unsuccessful');
}
}
This is a lot better, but I was hoping to avoid async/await
, and the need to use .toPromise()
on Observables.
What's the recommended way to chain these 3 api-calls?