【问题标题】:Return length of json array from observable when subscribe function has finished订阅函数完成后,从 observable 返回 json 数组的长度
【发布时间】:2019-07-25 18:36:13
【问题描述】:

我有一个函数可以获取其中包含 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,则会显示正确的值。

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

【问题讨论】:

  • 您遇到的问题是您将异步段代码视为同步

标签: angular subscribe


【解决方案1】:

而不是订阅 Observable。您可以通过.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;
    }
  }

当您调用此函数时,您必须先在 async 函数中调用它,然后再使用 await,如果您不这样调用它,它将仅返回 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)});
}

【讨论】:

  • 我试过了:我得到这个响应:ZoneAwarePromise {zone_symbol__state: null, _zone_symbol_value: Array(0)} _zone_symbol i>_state: null _zone_symbol_value: [] __proto: Object
  • @MariumMalik 我已经尝试使用 jsonplaceholder 并且它正在工作。您能否将您的 http.get() 请求添加到问题中?
  • 您是否在this.productService.getAllProducts().toPromise(); 之前添加了await
  • 不!我想在这里等待。所以,在你的地方等待似乎是正确的
  • 好的,对不起。我找到了问题并更新了答案。
【解决方案2】:

现在我想到了两个选项:第一个是返回服务器调用并在您的组件中订阅它,或者返回一个承诺。

第一个选项:

在您的组件中:

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
        ]
    });
 }

【讨论】:

  • 在您的第二部分代码中,您将返回 this.productsLenth 和 this.productsService.getAllProducts。对我来说,它只返回第一个的值,而不是第二个(这基本上是必需的)
【解决方案3】:

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

 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;
 }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-05
    • 1970-01-01
    • 2016-11-12
    • 2017-11-24
    相关资源
    最近更新 更多