Angular2: Configuration 'name' conflicts w

2020-02-05 11:03发布

问题:

I have some components of which one with dynamic routes.

the dynamic routes are added as,

let config = [];
for(let i = 0; i < this.pages.length; i++) {
  config.push({
    path: this.pages[i].slug, 
    name : this.pages[i].name, 
    component: AnotherComponent,
  });
}
router.config(config);

whenever the component with dynamic route is loaded more than once, the routes are configured again and that results in configuration conflict.

Here's the plunk, The dynamic routes are loaded with the link users, clicking again on users after navigating away from user logs the below shown error to the console.

How do I fix it? Thank you for looking into this.

回答1:

Check if the route exists before adding it

for(let i = 0; i < this.pages.length; i++) {
  if(!router.registry.hasRoute(this.pages[i].name, UsersComponent)) {
    config.push({
      path: this.pages[i].slug, 
      name : this.pages[i].name, 
      component: PersonComponent,
      data : {
        name : this.pages[i].name,
        slug : this.pages[i].slug
      }
    });
  }
}

Plunker