If a developer uses Angular without knowing the power of RxJS the code can turn into a huge mass very fast.
When the inner observable needs a value from the outer observable, we can and must use mergeMap
!
As a result, we not just gonna have nicer and more readable code, but we can follow the async pipe pattern.
It has also performance advantages if the outer event triggers twice then the first execution will be canceled.
With mergeMap
@Component({
selector: 'app-root',
template: `
<div class="container">
{{ user$ | async | json }}
</div>
`,
styleUrls: ['./app.component.css'],
})
export class AppComponent {
user$: Observable<User | null> =
this.userService.getUserId().
pipe(mergeMap(id => this.userService.getUser(id)));
constructor(private userService: UserService) {}
}
Without mergeMap
@Component({
selector: 'app-root',
template: ` <div class="container">{{user | json}}</div> `,
styleUrls: ['./app.component.css'],
})
export class AppComponent implements OnInit {
user: User | null = null;
constructor(private userService: UserService) {}
ngOnInit(): void {
this.userService.getUserId().subscribe((userId) => {
if (userId) {
this.userService.getUser(userId).subscribe((user) => {
this.user = user;
});
}
});
}
}
I am a Full-stack [Angular, Java] freelancer developer, if you would like to contact me here are my contacts: