当subscribe函数完成时,从observable返回json数组的长度

问题描述 投票:2回答:3

我有一个函数可以获得带有json数组的observable,作为来自http get的响应:

 public getCountofProducts() {

        this.productService.getAllProducts().subscribe
        (
            (products) => {
                if (products!= null) {
                    this.productsLength = products.length;
                }
            }
        );
        return this.productsLength;
    }

功能用途:

public getItems()
{
this.items=[

count: this.getCountofProducts()

            ]
}

getAllproducts()response:返回带有数组值的observable

现在,函数返回'0',因为订阅函数没有完成,我得到初始值,即'0'

如果我在subscribe函数中执行console.log,则会显示正确的值。

订阅功能完成后,获取价值的方法是什么?

angular subscribe
3个回答
1
投票

而不是订阅Observable。你可以通过ObservablePromise变换为.toPromise()。您还需要在应用async的函数之前创建函数await并放置.toPromise()。然后,products数组将存储在名为products的变量中,之后您可以正常使用它。

例:

public async getCountofProducts() {
    const products = await this.productService.getAllProducts().toPromise();
    if(products !== null) {
      return products.length;
    } else {
      return 0;
    }
  }

当您调用此函数时,您必须使用asyncawait函数中调用它,如果您不这样调用它将只返回ZoneAwarePromise。除此之外,你还可以使用Promise访问像.then()这样的值。

//You can call it like this
public async someFunction() {
 console.log(await this.getCountofProduts);
}
//OR
public someFunction() {
  this.getCountofProducts().then((result) => {console.log(result)});
}

0
投票

现在我想到两个选项:第一个返回服务器调用并在组件中订阅它或者返回一个promise。

第一选择:

在您的组件中:

public getItems()
{
    this.productService.getAllProducts().subscribe((products: Array<any>) => {
        this.items=[
            count: products ? products.length : 0;
        ]
    });

}

第二种选择:

product.service.ts

getAllProducts(): Promise<any[]> {
    return this.http.get('YOUR_URL').toPromise();
}

你的电话会是这样的。

public getCountofProducts() {
    return this.productService.getAllProducts().then
    (
        (products) => {
            if (products!= null) {
                this.productsLength = products.length;
                return this.productsLength;
            }
        }
    );
}

在您的组件中:

public getItems()
{
    this.getCountofProducts().then((len:number) => {
        this.items=[
            count: len
        ]
    });
 }

0
投票

试试这个,如果有任何问题请告诉我

 public getCountofProducts() {
    this.productService.getAllProducts().subscribe
    (
      (products) => {
          if (products!= null) {
             this.getCount(products);
             return this.productsLength;
           }
           else{
             return 0;
           }
       }
     );
 }

 public getCount(products){
    this.productsLength=this.products.length;
 }
© www.soinside.com 2019 - 2024. All rights reserved.