Should/How can I avoid this nested subscription using Angular materials dialog box

I currently have this set up:

this.entitiesManagementService.searchAddressEventEmitter$.pipe(switchMap((_) => {
  const formValue = this.addressAttributesSearchForm.getRawValue();
  return forkJoin([
    this.entitiesManagementService.getAddressClassification(new GetAddressClassificationPayload(<payloadValues>))),
    this.entitiesManagementService.searchAddress(new SearchAddressPayload(<payloadValues>))
  ])
})).pipe(this.takeUntilDestroyed()).subscribe(([fields, searchResults]) => {
  this.searchResults = searchResults
  this.fields = fields[0].addressFieldDetailDetails;

  const dialogRef = this.modalService.open(SelectAddressModalComponent, {
    data: {
      addresses: this.searchResults,
      fields: this.fields
    }
  })
  dialogRef.afterClosed().subscribe(selectedAddress => {
    console.log(selectedAddress)
  })
})

I’m wondering if theres a nice way that I can avoid the nested subscription, or whether its truly necessary?

If I understand correctly, the dialogRef.afterClosed() observable will always complete, so there probably isn’t a concern with that subscription staying open, but I suppose I should probably avoid the nested subscription.

Can anyone advise on how I can do this?

>Solution :

You can also use switchMap for this.

this.entitiesManagementService.searchAddressEventEmitter$.pipe(
  switchMap((_) => {
    const formValue = this.addressAttributesSearchForm.getRawValue();
    return forkJoin([
      this.entitiesManagementService.getAddressClassification(new GetAddressClassificationPayload(<payloadValues>))),
      this.entitiesManagementService.searchAddress(new SearchAddressPayload(<payloadValues>))
    ]);
  }),
  tap(([fields, searchResults]) => {
    this.searchResults = searchResults
    this.fields = fields[0].addressFieldDetailDetails;
  }),
  switchMap(([fields, searchResults]) => {
    return this.modalService.open(SelectAddressModalComponent, {
      data: {
        addresses: this.searchResults,
        fields: this.fields
      }
    }).afterClosed();
  }).
).subscribe(selectedAddress => console.log(selectedAddress));

Leave a Reply