0

I am new to Angular (used AngularJs for a number of years) and I am struggling with Observables :( I have this method:

filterProducts(categoryId: string, questions: Question[], organisationId: string): Observable<any> {
  var formulas = this.formulaService.getFromSelectedAnswers(questions);
  let shouldFilter = this.shouldFilterProducts(categoryId, questions, formulas);
  if (!shouldFilter) return;

  return this.filterOrScore(categoryId, organisationId, formulas).pipe(map(products => {
    if (!products || !products.length) return;

    this.products.length = 0;
    this.products.push.apply(this.products, products);
    this.questionService.filterQuestionsByProducts(products, questions);      
    this.questionService.updateSession(questions);
  }));
}

The line if (!shouldFilter) return; is not right. I need it to return an Observable so my subscriptions work. Does anyone know how to do that?

billyjov
  • 2,778
  • 19
  • 35
r3plica
  • 13,017
  • 23
  • 128
  • 290
  • https://stackoverflow.com/a/42645650/9839191 – Oram Oct 07 '18 at 13:37
  • 2
    Possible duplicate of [Return an empty Observable from an Angular2 Service](https://stackoverflow.com/questions/42645268/return-an-empty-observable-from-an-angular2-service) – ConnorsFan Oct 07 '18 at 13:41

1 Answers1

2

You can return empty, if you don't care about return values in subscription. which will complete the observable.

import {empty} from 'rxjs';

filterProducts(categoryId: string, questions: Question[], organisationId: string): Observable<any> {
  var formulas = this.formulaService.getFromSelectedAnswers(questions);
  let shouldFilter = this.shouldFilterProducts(categoryId, questions, formulas);
  if (!shouldFilter) return empty();

  return this.filterOrScore(categoryId, organisationId, formulas).pipe(map(products => {
    if (!products || !products.length) return empty();

    this.products.length = 0;
    this.products.push.apply(this.products, products);
    this.questionService.filterQuestionsByProducts(products, questions);      
    this.questionService.updateSession(questions);
  }));
Suresh Kumar Ariya
  • 9,516
  • 1
  • 18
  • 27