Hi there I am a little new to angular and I am having trouble with loading data. In the snippet of code below I have two services getting called. In each service I output something to the console. After both of the services run I have a piece of code that outputs my order number to the console an additional time. However every time I run this. It blazes thru ngOnInit and puts out the info below in the console. How can i tell the last console output to wait until the first two services are completely done.
length of depots 18
ngOnInit(): void {
//called first
this.dataService.sendGetRequest().subscribe((data: any[]) => {
this.orderInfoList = data;
console.log("array of depots "+ this.orderInfoList.depots[1].name);
console.log("length of depots "+ this.orderInfoList.depots.length);
})
//called second
this.dataService.getOrder(+this.orderId).subscribe((data: any[]) => {
this.order = data;
console.log("order " + this.order.orderNumber);
})
//entered last
console.log("order " + this.order.orderNumber);
}
The data service functions are asynchronous, so you need to run them asynchronously. Since getOrder
doesn't depend on the result of sendGetRequest
, you can run them in parallel using forkJoin
.
They will both be executed, and the subscribe will only run once both have completed.
ngOnInit(): void {
forkJoin({
getRequest: this.dataService.sendGetRequest(),
order: this.dataService.getOrder(+this.orderId)
}).subscribe(result => {
this.orderInfoList = result.getRequest;
this.order = result.order;
console.log("array of depots "+ this.orderInfoList.depots[1].name);
console.log("length of depots "+ this.orderInfoList.depots.length);
console.log("order " + this.order.orderNumber);
});
}
forkJoin
also accepts an array of observables:
forkJoin([
this.dataService.sendGetRequest(),
this.dataService.getOrder(+this.orderId)
]).subscribe(result => {
this.orderInfoList = result[0];
this.order = result[1];
});