In my current project, I am faced with the challenge of sending two HTTP requests sequentially. The goal is to send the second request only if the first one is successful, and if not, display an error message related to the failed initial request.
My approach involves using Angular's HttpClient module, as shown in the code snippet below:
import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'app-root',
templateUrl: 'app/app.component.html'
})
export class AppComponent {
loadedCharacter: {};
constructor(private http: HttpClient) {}
ngOnInit() {
this.http.get('/api/people/1').subscribe(character => {
this.http.get(character.homeworld).subscribe(homeworld => {
character.homeworld = homeworld;
this.loadedCharacter = character;
});
});
}
}
I am aware of alternative methods such as forkjoin
, mergemap
, but I find this particular approach more readable and suited to my specific use case. Are there any thoughts or suggestions on how to improve this solution?