Search code examples
angulartypescriptobservable

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 a 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

  • 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