Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Trigger error or complete from a subscribe

I’m new to Angular and I’m trying to trigger the error callback in a subscribe. I’m manipulating a table object and want to throw a toast when an trigger becomes true. Either via an error or complete.

// editCollection.component.ts
handleMoveRowsDown() {
  this.collectionsStore.moveRowsDown(this.selectedRows).subscribe(
    (collection) => {
      this.table.sorts = [];
      this.rowsSorted = true;
      this.collection = collection;
      this.table.rows = this.collection.rows;
    },
    (error) => {
      console.error(error);
      this.toastr.error("You've hit bottom!"); // throw toast if "trigger" is true
      this.selectedRows = [];
    }
  );
}
// collections.store.ts
moveRowsDown(selectedRows: DtRow[]): Observable<DtCollection> {
  let trigger = false;
  
  // manipulate table... 

  if (trigger) {
    throw new Error(); // this does not work
  } else {
    this.setCurrentCollection(tempCollection as DtCollection);
    // how do I return trigger along with the asObservable?
    return this._currentCollection.asObservable(); 
  }
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Return an observable with error instance via throwError().

return throwError(() => new Error());
import { throwError } from 'rxjs';

moveRowsDown(selectedRows: DtRow[]): Observable<DtCollection> {
  let trigger = false;
  
  // manipulate table... 

  if (trigger) {
    return throwError(() => new Error());
  } else {
    this.setCurrentCollection(tempCollection as DtCollection);
    // how do I return trigger along with the asObservable?
    return this._currentCollection.asObservable(); 
  }
}

Dummy Demo @ StackBlitz

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading