I am trying to create a component that subscribes to the id url parameter in the activated route, and then uses it to call a service of mine that makes an http request to a server with the id.
I have a route that takes in an id like so - /article/view/1005
Previously, I was not subscribing to the url parameters, and I was just grabbing the id from the url once.
This was the code in the class then:
ngOnInit() {
var id = +this.activatedRoute.snapshot.params["id"];
if (id) {
this.articleService.get(id).subscribe(
article => this.article = article
);
}
else if (id === 0) {
console.log("id is 0: switching to edit mode...");
this.router.navigate(["article/edit", 0]);
}
else {
console.log("Invalid id: routing back to home...");
this.router.navigate([""]);
}
}
However, I have come across the situation where the same component can be routed to repeatedly but with different ids each time and the ngOnInit hook is only firing the first time. So I want to subscribe to the id in the url parameters to address that problem.
I tried finding a solution, and it looks like a flatmap is what I want to use. However, I can't find a good source that shows how I would link a subscription to the url parameters like this
this.activatedRoute.params.subscribe((params: Params) => {
id = params['id'];
console.log(params);
})
to the subscription to my article service.