我有一个从 API 获取数据的 Angular 应用程序。所以首先我的detail.component.ts代码看起来像这样:
//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
}
正如你所看到的,由于将所有这些调用相互嵌套,我将来的调用越多,它就会变得越混乱。我做了一些研究,得到了observables可以解决问题的想法。所以我更改了代码,这就是现在的样子 - 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;}
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必须首先执行,因为Data2和Data3需要来自Data1的过滤后的 Array 的信息。这就是为什么我很难应用像forkJoin这样的解决方案。所以我的问题是,如果这是一个好的解决方案,或者您是否知道更好的方法来减少代码混乱并保持功能?