0

I'm trying to make file upload in Angular2. I use the code that I found here - https://plnkr.co/edit/ozZqbxIorjQW15BrDFrg?p=info.

I need to use response in my epic (Angular2 + Redux) so I would like to do something like:

updateAvatarRequest = (action$: ActionsObservable<IPayloadAction>) => {
    return action$.ofType(MeActions.UPDATE_AVATAR)
      .mergeMap<IPayloadAction>(({payload}) => {
        return this.meService.updateAvatar()
          .map(result => ({
            // ACTION ON SUCCESS
          }))
          .catch(error => Observable.of({
            // ACTION ON ERROR
          }));
        });
}

The problem is that I don't get any response from my Observable until I don't subscribe it. The other problem is that I couldn't use catch() on this observable. It works if I do it this way:

this.meService.updateUserAvatar(formData)
    .subscribe(
      (x) => console.log('onNext: %s', x),
      (e) => console.log('onError: %s', e),
      () => console.log('onCompleted')
);

But I want to be consistent. Please help me with this RxJS until I lose the rest of the hair.

Zacol
  • 93
  • 5

1 Answers1

2

I don't get any response from my Observable until I don't subscribe it

That's by design. I suppose action$.ofType(MeActions.UPDATE_AVATAR) returns a cold Observable so it's not triggered until there's at least one subscriber. You can use publish() to turn it into a ConnectableObservable and immediately call connect() which makes it a hot Observable (https://jsbin.com/faquhew/5/edit?js,console) but I think it's better to stick with the default functionality.

For more info see:

Operator catch() let's you continue the chain with an Observable returned from its callback, see: https://github.com/Reactive-Extensions/RxJS/blob/master/doc/api/core/operators/catch.md

So it depends on what you want to achieve with catch().

Edit:

var source = Observable.create(obs => {
    obs.next(1);
    obs.next(2);
    obs.error(new Error('original error message'));
  })
  .catch(error => Observable.of('recovered from error'));

source.subscribe(val => console.log(val));

This prints to console:

1
2
"recovered from error"

See live demo: https://jsbin.com/micebeg/4/edit?js,console

Community
  • 1
  • 1
martin
  • 93,354
  • 25
  • 191
  • 226
  • Do I need to throw an error if I want to use catch operator? Could you provide an example for catch usage? Thanks in advance :) – Zacol Nov 09 '16 at 18:32
  • @Zacol Operator `catch()` handles only error. It has no other purpose, see my update. – martin Nov 10 '16 at 08:58