【发布时间】: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,则会显示正确的值。
订阅函数完成后,获取值的方法是什么?
【问题讨论】:
-
您遇到的问题是您将异步段代码视为同步。