我如何在Angular中定义对Observables的订阅执行顺序?

问题描述 投票:0回答:3

我从service.ts文件中的API获得一些get-Call:

//code
getCars()
{
this.car = this.http.get(car_url)
return this.car;
}

getTires()
{
this.tires = this.http.get(tires_url)
return this.tires;
}

getSeats()
{
this.seats = this.http.get(seats_url)
return this.seats;
}

detail.compoenent.ts中,我将此数据过滤到选定的汽车,然后通过detail.component.html-[[detail.compoenent.ts呈现): >//code ngOnInit() { this.Service.getCars() .subscribe(cars => this.car = cars.find(/*code (selecting car with certain car_id*/) this.Service.getTires() .subscribe(tires => {this.tires = tires.filter(/*code (selecting all the tires with the selected car_id*/)} this.Service.getSeats() .subscribe(seats => {this.seats = seats.filter(/*code (selecting all the seats with the selected car_id*/)} }

要过滤轮胎和座椅,必须首先执行getCar(),因为需要其信息来过滤轮胎和座椅。因此,我该如何放置代码以确保在this.Service.getTires()。subscribe(/ 

code

/)之前执行此Service.getCars()subscribe(/ code /)和this.Service.getSeats()。subscribe(/ code /)?我从service.ts文件中的API获得了一些get-Call://代码getCars(){this.car = this.http.get(car_url)返回this.car; } getTires(){this.tires = this.http.get(tires_url)返回此值。...
angular typescript service observable subscription
3个回答
1
投票
简单的解决方案是在回调函数中发出后续的http请求。

1
投票
具有嵌套订阅是一种很大的代码味道。如果您需要嵌套订阅,请搜索更高阶的可观察对象,例如switchMap,concatMap,mergeMap,zip等。

1
投票
您可以使用mergeMap()并随后调用其他可观察对象,也可以在另一个API中使用其他先前API的数据。
© www.soinside.com 2019 - 2024. All rights reserved.