0

I have a form that creates an item in the backend, and optionally another resource depending if the user selects a checkbox. The second resource has to be created only after the first one is. I have come up with this code, but I don't think it's the right way to do it, especially the part where the checkbox hasn't been checked and I have to return a nonsense Observable. Any help?

this.myService.createArticle(article)
  .flatMap(_ => {
    if (this.checkbox) {
      return this.mailer.createOtherResource(data);
    } else {
      return Observable.of('done');
    }
  });

I also tried returning an EmptyObservable, but it doesn't work.

Pizzicato
  • 1,473
  • 1
  • 16
  • 32
  • 1
    This looks similar: https://stackoverflow.com/questions/42705511/how-to-use-the-flatmap-operator-conditionally-angular-2-rxjs Although it's rxjs2, it should be applicable to rxjs6 as well – Capricorn Jul 11 '18 at 15:36
  • Sorry for the late answer! Yep, you are right, `filter()` or `takeWhile()` is what I was looking for. Cheers! – Pizzicato Jul 19 '18 at 11:24
  • 1
    Possible duplicate of [How to use the 'flatmap' operator conditionally ? (Angular 2/rxjs)](https://stackoverflow.com/questions/42705511/how-to-use-the-flatmap-operator-conditionally-angular-2-rxjs) – Pizzicato Jul 19 '18 at 11:25

1 Answers1

0

Even if this question is a duplicate of this question, there are some differences due to RxJS version. In RxJS 6 this would be done similarly to this:

this.myService.createArticle(article)
  .pipe(
    filter(() => this.checkbox),
    flatMap(() => return this.mailer.createOtherResource(data)),
  });
Pizzicato
  • 1,473
  • 1
  • 16
  • 32