Within componentOne.ts, I am sending data via the sharedService like this:
this.sharedService.sendData(this.getCheckedProduct);
In componentTwo.ts, I am subscribing to the data in this manner:
productList: any = [];
getAllProducts: any = [];
ngOnInit() {
this.sharedService.getData().subscribe(data => {
this.productList = data;
this.getProduct();
});
}
Upon receiving the data in productList, I then call the function this.getProduct()
which contains the following logic:
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;
}
The objective is to pass the element.product_obj_id
in order to retrieve the relevant data associated with that particular ID.
I attempted an alternate approach as follows:
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']);
}
Although the data is successfully retrieved inside the async getProduct(element)
function, I encounter issues displaying it in the HTML portion of the code:
HTML:
<div *ngFor="let product of getAllProducts">
Getting data
</div>
Switching to an async implementation results in an error:
<div *ngFor="let product of getAllProducts | async">
Getting data
</div>
The error message is:
ERROR Error: InvalidPipeArgument: '' for pipe 'AsyncPipe'
at invalidPipeArgumentError
To elaborate, the main goal is to send data from componentOne through sharedservice, receive it in componentTwo, extract the product_obj_id
from the received data, and subsequently fetch and store the final data from the service request. The ultimate aim is to populate the getAllProducts array with the acquired data.
AppConfig.settings.product.getProducts
represents the URL endpoint.
The challenge lies in effectively handling the data asynchronously, ensuring that the getAllProducts
array is populated with the final data fetched from the service call for each ID passed.
this.getAllProducts.push(asyncResult['data']);
works within the function but the retrieved value seems to be inaccessible outside the function, rendering getAllProducts
ineffective in the HTML section.
Previously, in scenario 1, I used:
this.getAllProducts = tempArray;
This method resulted in an empty array, prompting the shift to the async
approach.
In essence, the goal is to obtain the final data within this.getAllProducts
from the service, where an ID passed in the URL fetches the required information.