首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >订阅函数完成时,从observable返回json数组长度

订阅函数完成时,从observable返回json数组长度
EN

Stack Overflow用户
提问于 2019-03-04 20:35:12
回答 3查看 1.1K关注 0票数 2

我有一个函数,它获取包含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()响应:返回一个包含数组值的观察值

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

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

一旦订阅函数完成,获取值的方法是什么?

EN

回答 3

Stack Overflow用户

发布于 2019-03-04 20:50:17

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

示例:

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

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

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

Stack Overflow用户

发布于 2019-03-04 20:52:17

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

First选项:

在您的组件中:

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
EN

Stack Overflow用户

发布于 2019-03-05 15:03:29

试试这个,如果有什么问题请告诉我

 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;
 }
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54983405

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档