Home > Back-end >  angular - Error handling with nested subscriptions - Chain multiple api-calls
angular - Error handling with nested subscriptions - Chain multiple api-calls

Time:06-29

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?

CodePudding user response:

You should be able to re-write this logic in a more idiomatic rxjs way like this

register() {
    this.accountService.register(this.user, this.password, this.passwordConfirmation).pipe(
      concatMap(() => this.accountService.login(this.user.email, this.password)),
      concatMap((loginResult) => {
        if (loginResult.status === ELoginStatus.success) {
           return this.router.navigateByUrl(this.returnUrl)
        }
        throw new Error("Login unsuccessful")
      })
    )
    .subscribe({
      next: data => {
            // process any result in case of success
            },
      error: () => this.errorMessage$.next('Login unsuccessful')
    })
}

As you see i tend to use concatMap when i need to compose more than one call to http, since concatMap implies that we wait for the response of the previous call before we move to the second.

switchMap is the right operator if we want to "kill on fly requests' when new requests come in.

mergeMap should be used when you want to manage more requests in parallel, but it comes with its own complexities.

Maybe you can find some inspiration here.

  • Related