angular 中每条路线的通配符加载

wildcard loading for every route in angular

我在 angular 中将通配符路由添加到我的应用程序中。 问题是在添加通配符之后。

我不确定是什么问题! 下面是路由数组:

const appRoutes: Routes = [
    { path: 'login', redirectTo: '/login', pathMatch: 'full' },
    { path: 'settings', redirectTo: '/settings', pathMatch: 'full' },        
    { path: '**', component: PageNotFoundComponent }       
];

登录和设置是模块,它们有自己的路由文件。 在添加通配符和默认路由之前,应用程序在启动时被重定向到登录屏幕。

但现在每个 url 都被重定向到 PageNotFoundComponent 。

The order of the routes in the configuration matters and this is by design. The router uses a first-match wins strategy when matching routes, so more specific routes should be placed above less specific routes. In the configuration above, routes with a static path are listed first, followed by an empty path route, that matches the default route. The wildcard route comes last because it matches every URL and should be selected only if no other routes are matched first.

请指导! 谢谢

像这样使用它:确保您已按如下方式创建了所有组件

永远不要将通配符路由放在首位,因为它始终将通配符路径作为默认路径。

const appRoutes: Routes = [
    { path: '', component:AppComponent},
    { path: 'login', component:LoginComponent},
    { path: 'settings', component:SettingsComponent},
    { path: '**', component: PageNotFoundComponent }
];

尝试将 RouterModule 导入为 RouterModule.forRoot(routes, { useHash: true })

通配符路由需要是数组中的最后一个。现在,当您的应用程序启动时,路径是空的,因此路由器路由到与应用程序路由匹配的第一个特定路径,即通配符路由。当您更改顺序使通配符路由成为最后一个时,当您的应用程序启动时,它会发现它需要重定向到空路径上的登录,BEFORE 它会看到通配符路线,它将按预期工作。其次,不要重定向到同一条路线。为每个以组件为目标的路由使用特定组件。像这样更新你的路线数组。

const appRoutes: Routes = [
  { path: 'login', component: LoginComponent },
  { path: 'settings', component: SettingsComponent },
  { path: '', redirectTo: '/login', pathMatch: 'full'},
  { path: '**', component: PageNotFoundComponent }
];

编辑

OP 表示他们希望为应用程序中的不同功能模块使用单独的路由模块。为此,我知道您有两个选择。您可以使用 Lazy Loading, OR you can declare the routes pertaining to each feature module in its own Routing Module and then IMPORT the feature module into your app.module. The approach is demonstrated in the following stackblitz: https://stackblitz.com/edit/angular-q8mkac

请使用组件代替通配符:

 { path: 'login', component: LoginComponent , pathMatch: 'full'}