I need to subscribe to two different things in the ngOnInit of a given component:
- To a get request included in an Angular service already created, from which I will fetch a list of items (sourceOptions in the code).
- To the route.queryParams of my url, so I can use one of these params to call a function which will also use the list of items fetched in point 1.
The issue here is that I need somehow to concat them in a given order (1. then 2.) because the function called in 2 setSelected(params["sourceTool"] is using the list of items mentioned.
Could it be done with rxjs concat operator? How should it be coded?
Thanks
ngOnInit(): void {
this.searchApi.getSourceTools()
.subscribe(response => {
response.items.forEach((sourceTool: string) => {
this.sourceOptions.push({
description: sourceTool,
selected: false
})
})
})
this.route.queryParams
.subscribe(params => {
this.setSelected(params["sourceTool"])
})
}
CodePudding user response:
this.searchApi.getSourceTools()
.pipe(
tap(response => {
response.items.forEach((sourceTool: string) => {
this.sourceOptions.push({
description: sourceTool,
selected: false
})
})
}),
switchMap(() => this.route.queryParams)
)
.subscribe(params => {
this.setSelected(params["sourceTool"])
});
If I understand correctly your problem, you can easily use switchMap
operator to change the source observable after initial source emit value (with side effects execution)