Implementing higher order operators like concatMap
, switchMap
, exhaustMap
, and mergeMap
can enhance the functionality of your code. An example transformation could be seen below:
ngOnInit() {
this.http.get('localhost:8080/api/user').pipe(
mergeMap(({id: userId}) => {
const headers = new HttpHeaders({
'userId' : user.id
});
return this.http.get('localhost:8080/api/posts', {headers})
})
).subscribe(post => this.posts = post)
}
If you have the ability to modify the backend, it is recommended to update your api to posts/:id
instead of passing it as a header. This can be achieved as shown below:
ngOnInit() {
this.http.get('localhost:8080/api/user').pipe(
mergeMap(({id: userId}) => this.http.get(`localhost:8080/api/posts/${userId}`)
).subscribe(post => this.posts = post)
}
Additionally, integrating async
pipes can simplify your code and handle subscriptions automatically, making maintenance easier. Here's how you can update your TS file and html:
In your TS file
user$ = this.http.get('localhost:8080/api/user');
posts$ = this.user$.pipe(
mergeMap(({id: userId}) => this.http.get(`localhost:8080/api/posts/${userId}`)
)
and in your html
<div *ngFor='let post of posts$ | async'>
<!-- post variable accessible here -->
</div>