In my Angular application, I am retrieving data from APIs. Initially, my code in detail.component.ts looked like this:
//code
getData() {
this.http.get(url1).subscribe(data1 => {
/* code: apply certain filter to get a filtered array out */
this.http.get(url2).subscribe(data2 => {
/* code: apply certain filter to get a filtered array out */
this.http.get(url3).subscribe(data3 => {
/* code: apply certain filter to get a filtered array out */
}) // closing third subscribe form
}) // closing second subscribe form
}) // closing first subscribe form
}
As the number of calls increased, nesting them inside each other made the code messy. After some research, I discovered that using observables could help solve this issue. I refactored the code and now it looks like this in data.service.ts:
//code
getData1() {
this.data1 = this.http.get(this.url1)
return this.data1;
}
getData2() {
this.data2 = this.http.get(this.url2)
return this.data2;
}
getData3() {
this.data3 = this.http.get(this.url3)
return this.data3;
}
In detail.component.ts:
//code
ngOnInit() {
this.dataService.getData1().subscribe(data1 => {
/* code: apply certain filter to get a filtered array out */
this.dataService.getData2().subscribe(data2 => {
/* code: apply certain filter to get a filtered array out */
this.dataService.getData3().subscribe(data3 => {
/* code: apply certain filter to get a filtered array out */
}) // closing third subscribe form
}) // closing second subscribe form
}) // closing first subscribe form
}
Data1 must be executed first as Data2 and Data3 require information from the filtered Array obtained by Data1. This is why implementing solutions like forkJoin has been challenging. Is there a better approach to tidy up the code and maintain its functionality?