包装回调API并侦听错误?

时间:2018-11-04 00:30:47

标签: javascript node.js typescript rxjs

我正在包装这样的回调API:

%runscript

我想打电话:

    export function process(data: string): Observable<Result> {
      return Observable.create((observer: Observer<Result>) => {
        call(data, result => {
            if (result.errors) {
              observer.error(result.errors);
            }
            else {
              observer.next(result);  
            }
            observer.complete();
          },
        });
      });
    }

I've been reading through the documentation on catchError

该示例以如下方式结束:

process(data).subscribe(data=>doStuffWithData).catch(e=>performErrorHandling);

所以现在看来​​,我们在订阅时要么得到结果,要么得到错误。是否可以将像这样的值与错误分开:

//output: 'I caught: This is an error'
const subscribe = example.subscribe(val => console.log(val));

1 个答案:

答案 0 :(得分:0)

好像错误处理程序已作为第二个参数传递给立即订阅(subscribe(v=>{...}, e=>handleTheError):

result.subscribe(v=>console.log(v), error=>console.log(error));

有关更多信息,请参阅Angular大学的rxjs-error-handling

这是他们的HTTP示例:

http$.subscribe(
  res => console.log('HTTP response', res),
  err => console.log('HTTP Error', err),
  () => console.log('HTTP request completed.')
);

当您要发出备用后备值时,请使用catchError运算符。