Angular router '**' wildcard as a catch-al

2019-03-20 05:05发布

问题:

I've been experimenting with dozens of configurations trying to get this to work but cannot figure this out.

Given url as follows:

  • https://domain.com Dashboard
  • https://domain.com/profile Profile
  • https://domain.com/anything ...catch all with children.
    • https://domain.com/anything/edit
  • https://domain.com/otherthing
    • https://domain.com/otherthing/edit

anything and otherthing can literally be anything.

A route configuration I hoped would work but ends up taking over the defined routes where https://domain.com/profile would trigger the catchall ('**'), which seems very odd since to my understanding, the catchall should only fire or catch routes that are not defined above it:

Where app.module has this:

export const routes = [
  {
    path: '',
    loadChildren: 'app/dashboard/dashboard.module'
  },
  {
    path: 'profile',
    loadChildren: 'app/profile/profile.module'
  },
  {
    path: '**',
    loadChildren: 'app/anything/anything.module'
  }
];

@NgModule({
  imports: [
    BrowserModule,
    RouterModule.forRoot(routes)
  ],
  declarations: [AppComponent]
  bootstrap: [AppComponent]
})
export class AppModule {}

Where anything.module has this:

const routes = [
  {
    path: ':id',  // hoping to pick up the wildcard as param this way
    component: AnyComponent,
    children: [
      {
        path: 'edit',
        component: EditComponent
      }
    ]
  }
];

@NgModule({
  imports: [
    CommonModule,
    RouterModule.forChild(routes)
  ],
  declarations: [
    AnyComponent,
    EditComponent
  ]
})
export default class AnythingModule {}

Is there anyway to make the above use case work with the Angular Router 3.4.1?

回答1:

If ProfileModule doesn't have a path: '' route, then there is no route to match and the router continues to match remaining routes.



回答2:

This was asked a year ago. However I was using Angular 5.1.2 and found myself with the same problem

This was a bug with the router solved on issue #18139, I updated to 5.2.1 on my package.json to get the fix

"@angular/core": "^5.2.1",
"@angular/forms": "^5.2.1",
"@angular/http": "^5.2.1",

etc...