不同路线相同的组件

时间:2016-09-28 16:00:34

标签: angular angular2-routing

我希望实现这样的目标/products显示所有产品,/products/:category显示与特定类别相关的所有产品。为实现这一点,我有以下路线:

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

问题

当我在类别之间切换时,一切都很好,当我在所有产品和类别产品之间切换时,反之亦然,Angular重新绘制组件并且闪烁。

Angular 2路由器最终版本没有Regex,据我所知。有什么东西我不知道,或者现在这是唯一的解决方案吗?

4 个答案:

答案 0 :(得分:7)

你可以通过添加路线解决它

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

并在ExperienceComponent导入

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

并在构造函数中添加此参数

constructor(public route: ActivatedRoute)

和内部构造函数获取url

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

答案 1 :(得分:5)

我不知道是否有其他方法可以做到这一点,但我设法使用以下黑客工作。

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 {
}

处理ListComponent上的路径更改:

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

在ListComponent模板上添加路由器插座。

答案 2 :(得分:3)

您还可以定义到特定路径的重定向:

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

其中/home是您要重定向到的路线。

path: '**'解析所有未定义的路径

答案 3 :(得分:0)

您可以使用重定向来解决它,

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

除非有匹配的路径,否则更像是将默认路径设置为一个。

相关问题