简体   繁体   English

如何抛出Observable错误

[英]How to throw an Observable error

I have this method in Angular 4 : 我在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. 我想控制是否有任何输入参数为null并且如果它发生则不调用http.put()然后抛出必须在调用此参数subscribe()方法中http.put() 的错误

I tried with this and some combinations like throw Observable.throw('Error') but I can't get it to work. 我尝试了这个和一些组合,如throw Observable.throw('Error')但我无法让它工作。

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. Observable.throw应该有效。 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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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