0

I am trying to catch an error with ngrx and angularfire2 firetore.

Here is the effect

@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 )));

and actions:

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');
 }
}

I keep getting success even if the action is not completed. What is the good way to do this?

LearnToday
  • 2,762
  • 9
  • 38
  • 67

1 Answers1

2

Currently, this code is trying to catch errors on the entire stream, rather than the inner observable that matters.

Try this:

@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))
  });

See the docs on mergeMap and this helpful answer on SO about it. The stream that may throw an error is the internal of(this.afs.doc...) observable, so the .catch should be on that observable. In the current implementation (from your example above), it will always map the result of of(this.afs.doc...) to a new actions.Success(), whether it fails or not.

vince
  • 7,808
  • 3
  • 34
  • 41
  • Thanks for the response. Unfortunately, I tried that but it didn't work as expected. – LearnToday Feb 01 '18 at 03:37
  • Then the issue must be with some other part of your code. The code I've provided will work if the rest of your code is fine. I'd look into what that `.delete()` method is returning and see if it is already an Observable. – vince Feb 01 '18 at 17:13