1

I'm having this problem, I have a ProductService that has a boolean function validateProductsBeforeChanges.

Inside validateProductsBeforeChanges I call a function from another service called OrderService which returns an observable.

Some example code:

validateProductsBeforeChanges(idProduct): Boolean {
     this._orderService.getAll()
         .subscribe(orders => {
               this.orders = orders;
               this.ordersWithCurrentMenu = this.orders.filter(x => 
                                                               x.products.find(y => y.code == idProduct));

               if(this.ordersWithCurrentMenu.length > 0) {
                   return false;
               }
               else {
                   return true;
               }
         });
}

The problem is that vs code throws a syntax error:

A function whose declared type is neither 'void' nor 'any' must return a value

So I tried doing something like this:

validateProductsBeforeChanges(idProduct): Boolean {
     this._orderService.getAll()
         .subscribe(orders => {
              this.orders = orders;
              this.ordersWithCurrentMenu = this.orders.filter(x => x.products.find(y => y.code == idProduct));

              if (this.ordersWithCurrentMenu.length > 0) {
                  return false;
              }
              else {
                  return true;
              }
         });

    return false;
}

But in that case, the last return gets executed before the .subcribe ends and the function always returns false.

Any ideas on how to solve this?

Thank you very much!

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • Change `.subscribe(` to `.pipe(map(` with map coming from “rxjs/operators”. And add a return in front of everything. What ever is consuming this will need to subscribe instead. Return type would change to `Observable`. – Alexander Staroselsky Apr 27 '19 at 03:32
  • Possible duplicate of [angular 2 how to return data from subscribe](https://stackoverflow.com/questions/39295854/angular-2-how-to-return-data-from-subscribe) – Alexander Staroselsky Apr 27 '19 at 03:39

1 Answers1

1

Something like this:

validateProductsBeforeChanges(idProduct): Observable<Boolean>{
  return this._orderService.getAll()
  .pipe(
      map(orders => 
       orders.filter(x => x.products.find(y => y.code == idProduct))
             .map(filtered => filtered <= 0)
      )          
   );
}

Use like this:

validateProductsBeforeChanges(id).subscribe(t=> {
     if (t) {
        ...
     }
     else {
       ...
     }
})
Michael Kang
  • 52,003
  • 16
  • 103
  • 135