在componentOne.ts中,我通过sharedService发送数据,
this.sharedService.sendData(this.getCheckedProduct);
在 componentTwo.ts 中,我订阅的数据如下:
productList: any = [];
getAllProducts: any = [];
ngOnInit() {
this.sharedService.getData().subscribe(data => {
this.productList = data;
this.getProduct();
});
}
我在产品列表中获取数据,然后我需要调用函数this.getProduct()
,它具有以下内容,
getProduct() {
let tempArray = [];
this.productList.forEach(element => {
this.appService.getRest(AppConfig.settings.product.getProducts + '/' + element.product_obj_id).subscribe(res => {
tempArray.push(res.data);
});
});
this.getAllProducts = tempArray;
}
我需要传递 id element.product_obj_id
来获取该 id 的必要数据..
我尝试过像这样改变上面的内容,
ngOnInit() {
this.sharedService.getData().subscribe(data => {
data.forEach(element => {
this.getProduct(element);
})
});
}
async getProduct(element) {
let asyncResult = await this.appService.getRest(AppConfig.settings.product.getProducts + '/' + element.product_obj_id).toPromise();
this.getAllProducts.push(asyncResult['data']);
}
在async getProduct(element)
函数中,我正在获取this.getAllProducts
的数据,但在html中我没有获取数据。
HTML:
<div *ngFor="let product of getAllProducts">
Getting data
</div>
如果我用异步更改了上面的内容
<div *ngFor="let product of getAllProducts | async">
Getting data
</div>
我收到错误,
ERROR Error: InvalidPipeArgument: '' for pipe 'AsyncPipe'
at invalidPipeArgumentError
详细解释一下,我需要通过 componentone 中的共享服务发送数据并在 componenttwo 中接收数据,然后需要从该共享服务数据中获取 product_obj_id
。
在传递每个 id 时,我将获取该特定产品的数据,并且我需要存储从 this.appService.getRest(AppConfig.settings.product.getProducts + '/' + element) 收到的最终数据.product_obj_id).toPromise();
到 getAllProducts..
AppConfig.settings.product.getProducts
是网址..
如何以异步方式实现它..到目前为止我正在获取数据
this.getAllProducts.push(asyncResult['data']);
但在函数之外我没有获得值,而且 getAllProducts
不再适用于 html 中的任何场景..
在这个问题顶部解释的场景1中,我给出了以下内容
this.getAllProducts = tempArray;
这个给出了空数组作为值,所以只有我正在尝试使用async
函数。
简单来说,我需要从 this.getAllProducts
获取最终数据,该数据将从 service
使用 get 方法接收,我需要为其传递 id网址..
最佳答案
只需在异步调用中分配数据,如下所示 -
getProduct() {
let tempArray = [];
this.productList.forEach(element => {
this.appService.getRest(AppConfig.settings.product.getProducts + '/' + element.product_obj_id).subscribe(res => {
tempArray.push(res.data);
this.getAllProducts = tempArray; // Here
});
});
}
PS:在您的用例中,无需使用管道async
。
关于javascript - 如何在 Angular 中制作异步函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53493120/