简体   繁体   English

如何从订阅另一个函数的可观察函数的函数返回布尔值?

[英]How to return boolean value from a function that subscribes to an observable of another function?

I'm having this problem, I have a ProductService that has a boolean function validateProductsBeforeChanges . 我遇到了这个问题,我有一个具有布尔函数validateProductsBeforeChangesProductService

Inside validateProductsBeforeChanges I call a function from another service called OrderService which returns an observable. validateProductsBeforeChanges内部,我从另一个名为OrderService服务中调用一个函数,该函数返回一个可观察的对象。

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: 问题是vs代码引发语法错误:

A function whose declared type is neither 'void' nor 'any' must return a value 声明类型既不是“ void”也不是“ any”的函数必须返回一个值

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. 但是在这种情况下,最后一个返回值在.subcribe结束之前执行,并且该函数始终返回false。

Any ideas on how to solve this? 关于如何解决这个问题的任何想法?

Thank you very much! 非常感谢你!

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 {
       ...
     }
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM