Search code examples
angularobservable

Angular: How to throw an error inside an Observable


openModelSearchDialog() {
   const addRef = this.dialog.open(DiscoverModelEntryDialogComponent, {
      width: '600px',
      autoFocus: true,
      disableClose: true,
      data: []
   });
   addRef.afterClosed().subscribe(models => {
      if (models.length > 10) { 
          console.log("Oops, we got more than 10 models");
      }
       this.models = models;
       this.changeDetector.detectChanges();
   });
}

I tried the following:

addRef.afterClosed().subscribe(
   (models) => {
     this.models = models;
     this.changeDetector.detectChanges();
   },
   (error) => {
     if (this.models.length > 10) {
       console.log('Oops, we got more than ten models', error);
     }
   }
 )

I believe I have to use a pipe() but if so, I am not implementing it correctly:

addRef
   .afterClosed()
   .pipe(error => {
     if (this.models.length > 10) {
       return error;
     }
   })
   .subscribe(models => {
     this.models = models;
     this.changeDetector.detectChanges();
   });

Solution

  • Simple version of this will be after you subscribe You can check res

    if (this.countries.length>10) {
    throw throwError(response);  
    }
    

    Import through error from rxjs and you will be able to catch your error

    ,
    (error) => {
       console.log(error) 
     }
    

    }