如何使用 ngrx 捕获错误

How to catch error with ngrx

我正在尝试捕获 ngrx 和 angularfire2 firetore 的错误。

效果如下

@Effect()
        delete$: Observable<Action> = this.actions$
        .ofType(actions.DELETE)
        .map((action: actions.Delete) => action.id)
        .mergeMap(id => 
         of(this.afs.doc<Collection(`collections/${id}`).delete()))
        .map(() =>  new actions.Success())
        .catch(err => of (new actions.Fail(err.message )));

和操作:

export class Success implements Action {
  readonly type = SUCCESS;
  constructor() {
    console.log('success')
   }
}


export class Fail implements Action {
  readonly type = ERROR;

  constructor(public payload: any) {
    console.log('failed');
 }
}

即使行动没有完成,我也一直在成功。这样做的好方法是什么?

目前,此代码试图捕获整个流的错误,而不是重要的内部可观察对象。

试试这个:

@Effect delete$: Observable<Action> = this.action$
  .ofType(actions.DELETE)
  .map((action: actions.Delete) => action.id)
  .mergeMap(id => { 
    return of(this.afs.doc<Collection(`collections/${id}`).delete())
      .map(() =>  new actions.Success())
      .catch(err => of(new actions.Fail(err.message))
  });

请参阅 mergeMap and 上的文档。可能引发错误的流是内部 of(this.afs.doc...) 可观察对象,因此 .catch 应该在该可观察对象上。在当前的实现中(从上面的示例中),它总是 map of(this.afs.doc...) 的结果到 new actions.Success(),无论它是否失败。