Rishav Tandon
Rishav Tandon

Reputation: 1261

How to better write Subscribe within Subscribe Angular?

I have a dialog and I subscribe to its afterclosed() method and if the result is true I call another service and subscribe to it.

I dont want to have a subscribe within a subscribe.

What is the better way to write it? I suppose Rxjs operators can help but how and why its better approach?

dialog.afterClosed().subscribe((result) => {
      if (result) {
        this.projectService.deleteProject(name).subscribe(
          () => {
            this.getProjects();
          },
          (error) => {
            this.alertify.error(error);
          }
        );
      }
    });

Upvotes: 0

Views: 468

Answers (1)

Barremian
Barremian

Reputation: 31135

You could use one of the RxJS higher order mapping operators switchMap, concatMap, flatMap (aka mergeMap) or exhaustMap. Each has their specific use case. You could find a good write up here.

I'll use switchMap for illustration. I am also returning RxJS EMPTY constant if the result from first request is false/undefined. It emits a complete notification without next or error. So neither of the functions this.getProjects() or this.alertify.error(error) is triggered.

import { EMPTY } from 'rxjs';
import { switchMap } from 'rxjs/operators';

dialog.afterClosed().pipe(
  switchMap(result => {
    if (result) {
      return this.projectService.deleteProject(name);
    }
    return EMPTY;                 // <-- complete without `next` or `error` notifications
  })
).subscribe(
  res => this.getProjects(),
  error => this.alertify.error(error)
);

Upvotes: 1

Related Questions