首页 > 解决方案 > 捕获并返回错误时,Rxjs 可观察到的抛出错误

问题描述

您好我收到此错误“您在预期流的位置提供了一个无效对象。当从我的效果调用此 http 请求时,您可以提供 Observable、Promise、Array 或 Iterable”。

deleteAccount(accountId: string): Observable<any> {
    return this.http.delete(FUNDING_ACCOUNT_DELETE_URL
      .replace(ACCOUNT_ID, accountId)).pipe(
        timeout(2000),
        catchError(err => { 
          return err; })
      );
  }

@Effect()
  paymentOptionRemove = this.actions
    .ofType(ActionTypes.PAYMENT_OPTION_REMOVE).pipe(
      switchMap((action: PaymentOptionRemoveAction) =>
        this.service.deleteAccount(action.payload).pipe(
          map(
            _ => new PaymentOptionRemovedAction()),
          // tslint:disable-next-line:arrow-return-shorthand
          catchError(err => {
            if (err) {
              console.log(err);
            }
            return of(new PaymentOptionRemoveErrorAction());
          })
        ))
    );

标签: angularrxjsangular6ngrx

解决方案


deleteAccount函数中,您应该返回一个Observable. 在catchError块中,您试图返回err,这是不可观察的。

使用throwError来自rxjs

throwError是一个来自 rxjs 的函数,它创建一个Observable只向订阅者发出错误的函数。专为您的用例而设计。

import { throwError } from 'rxjs';

在删除函数中,使用如下:

return throwError(err);  

推荐阅读