Get current route without parameters

前端 未结 12 1430
梦如初夏
梦如初夏 2021-01-01 09:08

I need to get my current route without params in Angular 2, I found a way to get the current route with params as follows:

 this.router.url

12条回答
  •  情深已故
    2021-01-01 09:13

    In my case I needed to compare the previous route and the new route, when changing only the :id on the url via router.navigate. Since I wanted the path without the different ids, I got the original path of the route:

    /* 
        Routes = [
            { path: 'main/details/:id', component: DetailComponent }
        ]
    
        previousRoute = '/main/details/1'
        newRoute      = '/main/details/2'
    */
    
    this.routeSubscription = this.router.events.filter((event) => event instanceof ResolveStart)
                                               .pairwise() // returns previous and current events
                                               .subscribe((ev: [ResolveStart, ResolveStart]) => {
    
        let sameRoute = ev[0].state.root.firstChild.routeConfig.path == ev[1].state.root.firstChild.routeConfig.path ?
                           ev[0].state.root.firstChild.routeConfig.path : undefiend;
        if (sameRoute) {
            // Same routes, probably different ids 
            console.log(sameRoute) // gives 'main/details/:id'
        } else {
            // Different routes
        }
    });
    

提交回复
热议问题