Subscribe to both route params and queryParams in Angular 2

前端 未结 7 1907
粉色の甜心
粉色の甜心 2020-12-14 00:45

I have set up the following routing system

export const MyRoutes: Routes = [
  {path: \'\', redirectTo         


        
7条回答
  •  情歌与酒
    2020-12-14 01:26

    Late answer, but another solution : Instead of subscribing to the params and queryparams I subscribe to the NavigationEnd event on the router. Fires only once and both params and queryparams are available on snapshot : (example for angular 4)

    this.router.events.filter(event=>event instanceof NavigationEnd)
       .subscribe(event=>{
           let yourparameter = this.activatedroute.snapshot.params.yourparameter;
           let yourqueryparameter = this.activatedroute.snapshot.queryParams.yourqueryparameter;
       });
    

    Regarding unsubscribing : yes it is true routing params, queryParams or navigation events subscriptions are automatically unsubscribed by the router, there is however one exception : if your route has children , when navigating between children, no unsubscribe will occur. Only when you navigate away from the parent route!

    E.g. I had a situation with tabs as child routes. In constructor of first tab component subscribing on route params to retrieve data. Each time I navigate from first to second tab and back another subscription was added resulting in multiplying the number of requests.

提交回复
热议问题