Reputation: 23
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!
Upvotes: 1
Views: 3546
Reputation: 52837
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 {
...
}
})
Upvotes: 1