Angular tricks to become a pro. RxJS operators
In this post, I have gathered the RxJS tricks that I use the most to boost my Angular applications.
- Avoid callback hell
Sometimes we have multiple nested calls. This happens when the information is dependent between calls, so the output of the first call is required in the input of the second one, and so on.
ngOnInit(): void {
this.service.getMatchByUsername(username).subscribe((match)=>{
console.log('match', match);
this.service.getSponsorsByMatchId(match.id).subscribe((sponsors)=>{
console.log('sponsors', sponsors);
for(let sponsor of sponsors){
this.service.getCampaignsBySponsor(sponsor.id).subscribe((campaign)=>{
console.log('campaign', campaign);
});
}
});
});
}
When working with observables, you won’t call subscribe()
very often. Instead, there are operators to combine observables together, forming a pipeline of operations that will end up in a single subscribe()
call.
In order to avoid this, the new code structure will consist of substituting subscribe()
for pipe()
which will contain the set of requests. Inside the pipe, we will have the observables returned from each service call connected one after the other.