繁体   English   中英

Angular 5 - 使用不同的URL路由到相同的组件

[英]Angular 5 - Routing to the same component with different URL's

我有以下路由应该路由到同一个组件,我可以通过使用以下结构使其工作。

const carModuleRoutes: Routes = [
    { path: 'car/:category/:carId', component: CarDetailComponent},
    { path: 'car/:carId', component: CarDetailComponent},
];

但我知道这不是一种标准的方法,有没有一种正确的方法来做同样的功能?

这是定义routes及其各自components的标准方法。 您在routing模块内,并且您正在尝试定义routes ,而不是components

因此,不要忽视将相同的component分组并为它们定义routes 你做了什么似乎是合适的。

编辑:

你的情况很简单,你可以简单地做:

const carModuleRoutes: Routes = [
    { path: 'car/:category/:carId', redirectTo : 'car/:carId', pathMatch : 'full'},
    { path: 'car/:carId', component: CarDetailComponent},
];

注意 :

在这种情况下,您的网址会发生变化,您可能会丢失:category的值,这可能在组件中很有用。 因此,最好指定多个指向同一组件的路由作为单独的案例。

我解决了需要使用以下方法使用相同组件导航到不同路由的问题:

/* My Grid route: */
const GridRoutes: Routes = [
    {
        path: 'grid',
        component: BasicLayoutComponent,
        children: [
            {
                path: '',
                component: ListItemComponent
            },
            {
                path : 'view-files/:id',
                component : ListItemComponent
            },
            {
                path : 'filter',
                component: ListItemComponent
            }
        ]
    }
];

@Component({
  templateUrl: './list-item.component.html',
})
export class ListItemComponent {

   ...
   ...

    /* Function to navigate */
    navigateToRoute(path: string) {
       this.router.navigate([ path ]);
    }
}

然后,在模板上调用导航功能( list-item.component.html )。

<a (click)="navigateToRoute('page/edit/' + dataItem.id)">Link</a>

希望有所帮助!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM