'Angular2 router listen to parameter changes
I have several links navigating as
http://localhost:4200/#/forward/services/our-services?category=1
http://localhost:4200/#/forward/services/our-services?category=2
http://localhost:4200/#/forward/services/our-services?category=3
I would like to fetch the value of category
Ive tried
this.sub = this._activatedRoute.params.subscribe(params => {
this.category = + params['category'];
console.log(params['category']);
});
The console.log() is only printend once ,
How can i ensure i capture whenever the value of category changes
This is what am using for navigation
<ul id="menu-services-menu" class="menu" *ngFor="let category of categories">
<li><a routerLinkActive="active" [routerLink]="['/forward/services/our-services']" [queryParams]="{ category: category.category }" >{{category.category}}</a></li>
</ul>
Solution 1:[1]
constructor(router:Router, route:ActivatedRoute) {
router.events
filter(e => e instanceof NavigationEnd)
.forEach(e => console.log(route.snapshot.params['category']);
}
Solution 2:[2]
You can also with Angular 2 (Angular 5 as of this writing) do this:
constructor(private router:Router) {
router.events.subscribe(data=>{
if(data instanceof ActivationEnd){
this.category = data.snapshot.params['category'];
}
});
}
Solution 3:[3]
Instead of subscribing the route.events and then have to check or filter the events is possible to subscribe the specific queryParams and just get the params. I think is a more clean solution for this problem. constructor(private route: ActivatedRoute, private router: Router) {}
ngOnInit() {
this.route
.queryParams
.subscribe(params => {
this.page = params['category'];
});
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Günter Zöchbauer |
| Solution 2 | John |
| Solution 3 | Mwiza |
