我有一个函数,它获取包含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,就会显示正确的值。
一旦订阅函数完成,获取值的方法是什么?
发布于 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;
}
}
当你调用这个函数时,你必须使用await
在async
函数中调用它,如果你不这样调用它,它将只返回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)});
}
发布于 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
]
});
}
发布于 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;
}
https://stackoverflow.com/questions/54983405
复制相似问题