Different routes of the same component

I want to achieve something like this /products shows all products and /products/:category shows all products related to a certain category. For this, I have the following routes:

 const productsRoutes: Routes = [ { path: 'products', component: ProductsComponent, children: [ { path: '', component: ProductsListComponent, }, { path: ':category', component: ProductsListComponent } ] } ]; 

Problem

When I switch between categories, everything is fine, when I switch between all products and product categories, and vice versa, Angular redraws the components and flickers there.

Angular 2 There is no regular expression in the final version of the router, as I know. Is there something that I am missing, or is this the only solution so far?

+14
source share
4 answers

you can solve this by adding routes

 const routes: Routes = [ { path: 'experience', children: [ { path: 'pending', component: ExperienceComponent }, { path: 'requests', component: ExperienceComponent }, ] }] 

and when importing ExperienceComponent

 import { ActivatedRoute } from "@angular/router"; 

and in the constructor add this parameter

 constructor(public route: ActivatedRoute) 

and inside the constructor get url

 this.route.url.subscribe(params => { console.log(params[0].path); }) 
+8
source

I don't know if there is another way to do this, but I managed to get it to work using the following hack.

 export const productsRoutes: Route[] = [ { path: 'products', component: ProductsComponent, children: [ { path: '', pathMatch: 'prefix', component: ProductsListComponent, children: [ { path: '', component: EmptyComponent, }, { path: ':category', component: EmptyComponent, }, ], }, ], }, ]; 

EmptyComponent:

 import { Component } from '@angular/core'; @Component({ selector: 'GemainEmpty', template: '<router-outlet></router-outlet>', }) export class EmptyComponent { } 

Process route changes in ListComponent:

 ngOnInit() { this.routerEventsSubscription = this.router.events.subscribe((evt) => { if (!(evt instanceof NavigationEnd)) { return; } //Code to reload/filter list } } 

And add the router socket to the ListComponent template.

+5
source

You can also define a redirect to a specific path:

 { path: '**', redirectTo: '/home', pathMatch: 'full' }, 

where /home is the route you want to redirect to.

path: '**' resolves all paths that are not defined

+3
source

You can solve this by redirecting,

 const productsRoutes: Routes = [ { path: 'products', component: ProductsComponent, children: [ { // path => '/products' path: '', redirectTo: ':category', }, { // path => '/products/:category' path: ':category', component: ProductsListComponent } ] } ]; 

This is more like setting one default path if there is no corresponding path.

0
source

Source: https://habr.com/ru/post/1257408/


All Articles