简体   繁体   中英

How to throw an Observable error

I have this method in Angular 4 :

modifyStock(id: number, quantity: number) {
  const url = `/item/${id}/modifyStock`;
  const body = { quantity: quantity };

  return this.http.put(url, body);
}

I want to control if any of the input parameters are null and just don't call the http.put() if it happens and then throw an error that must be catched in the subscribe() method that call this one.

I tried with this and some combinations like throw Observable.throw('Error') but I can't get it to work.

modifyStock(id: number, quantity: number) {
  if (id == null || quantity == null) {
    return Observable.throw('Error');
  }

  const url = `/item/${id}/modifyStock`;
  const body = { quantity: quantity };

  return this.http.put(url, body);
}

You can have your observer throw an error:

this.data = new Observable(observer => {
      setTimeout(() => {
          observer.next(42);
      }, 1000);

      setTimeout(() => {
          observer.next(43);
      }, 2000);

      setTimeout(() => {
         observer.error('bla');
      }, 2500);

      setTimeout(() => {
          observer.complete();
      }, 3000);
  });

Observable.throw should work. Make sure to import it correctly.

import { Observable } from "rxjs/Observable";
import 'rxjs/add/observable/throw';

You sould be able to use it as you've done in your example.

test() {
  this.modifyStock(1, null).subscribe(() => {
    console.log('success');
  }, 
  err => {
    console.log('error', err);
  })
}

modifyStock(id: number, quantity: number): Observable<any> {
  if (id == null || quantity == null) {
    return Observable.throw('Error');
  }

  const url = `/item/${id}/modifyStock`;
  const body = { quantity: quantity };

  return this.http.put(url, body);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM