FE-Deve
FE-Deve

Reputation: 13

How to use check condition with in concatMap/switchMap in angular 7

I Am trying to download a pdf form API response. API-1 will return the file name, with the filename as input to the API - 2, I will download the pdf. It works well for positive cases. If incase there is no fileName returned from API - 1, I should not call the API-2, instead I have to tell the user no File exists in a popupDialog.

this.pdf.pdfName(pdfInfo).pipe(
      tap(res => fileName = res.fileName),
//Inside concatMap am not able to handle this condition (getVersionPdfFile-observable/printEmptyAlert - just a matdialog)
      concatMap(res => !!res.fileName ? this.pdf.getVersionPdfFile(res.fileName) : this.printEmptyAlert())
    ).subscribe(fileResponse => {
      var newBlob = new Blob([fileResponse], { type: "application/pdf" });
      const data = window.URL.createObjectURL(newBlob);
      var link = document.createElement('a');
      link.href = data;
      link.download = fileName;
      link.click();
      window.URL.revokeObjectURL(data);
    });

Upvotes: 1

Views: 271

Answers (1)

Ritesh Waghela
Ritesh Waghela

Reputation: 3727

You can throw error (using throwError) when there is no file name and handle that error in error block:

Import throwError

import { throwError } from 'rxjs';


this.pdf.pdfName(pdfInfo).pipe(
   tap(res => fileName = res.fileName),
   concatMap(res => !!res.fileName ? this.pdf.getVersionPdfFile(res.fileName) : 
      throwError('No file name'))
   ).subscribe(fileResponse => {
        var newBlob = new Blob([fileResponse], { type: "application/pdf" });
        const data = window.URL.createObjectURL(newBlob);
        var link = document.createElement('a');
        link.href = data;
        link.download = fileName;
        link.click();
        window.URL.revokeObjectURL(data);
     }, (error) => {
        // Handle error here
        if(error === 'No file name'){
          this.printEmptyAlert();
        }
 });

Upvotes: 2

Related Questions