Search code examples
angulartypescriptserviceobservablesubscription

How can I define the execution order of subscription to Observables in Angular?


I have got some get-Calls from an API in a service.ts file:

//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;
}

In the detail.compoenent.ts I filter this data to a selected car and then present it through detail.component.html - detail.compoenent.ts looks like this:

//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*/)}
}

To filter for the tires and seats, getCar() has to be executed first because information of it is needed to filter for the tires and seats. So how do I have to put the code to ensure this.Service.getCars()subscribe(/code/) is executed before this.Service.getTires().subscribe(/code/) and this.Service.getSeats().subscribe(/code/)?


Solution

  • Simple solution could be make subsequent http requests in call back functions.

    ngOnInit() 
    {
        this.Service.getCars().subscribe(
          cars => {
               this.car = cars.find();
               this.Service.getTires().subscribe(tires => {
                  this.tires = tires.filter();
                  this.Service.getSeats().subscribe(
                    seats => {this.seats = 
                  seats.filter(/*code (selecting all 
                     the seats with the selected car_id*/)}
                }
             }
    
          });
    
    }
    

    until all data is getting loaded you can show spinner to end user.