Different routes same component

后端 未结 4 1467
眼角桃花
眼角桃花 2021-01-01 12:06

I want to achieve something like this /products shows all the products and /products/:category shows all the products related to a specific categor

4条回答
  •  天命终不由人
    2021-01-01 12:16

    I don't know if there is another way to do this but I managed to make it 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: '',
    })
    export class EmptyComponent {
    }
    

    Handle route changes on the ListComponent:

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

    And add a router outlet on the ListComponent template.

提交回复
热议问题