我在 Angular 项目的路由方面遇到了一些问题,主要是子路由的第三层。在应用程序上导航时,路线运行良好。 ( routerLink
) 并且通过浏览器 URL 访问 URL 时出现问题。
我的 Angular 版本是 2.4.0
我正在使用 ng serve
在开发服务器上进行测试.
对于给定结构的项目,
.
├── photos
├── posts
├── users
│ ├── detail
│ │ ├── address
│ │ ├── family
│ │ ├── information
│ │ └── phones
│ ├── friends
│ └── profile
└── videos
下面是代码,
// user routes
export const userRoutes : Routes = [
{
path: 'detail',
component: DetailComponent
},
{
path: 'friends',
component: FriendsComponent
},
{
path: 'profile',
component: ProfileComponent
}
]
//app routes
const appRoutes: Routes = [
{
path: '',
component: HomeComponent
},
{
path: 'photos',
component: PhotosComponent
},
{
path: 'posts',
component: PostsComponent
},
{
path: 'users',
component: UserListComponent
},
{
path: 'user/:username',
component: UserComponent,
children: userRoutes
},
{
path: 'videos',
component: VideosComponent
}
]
export const AppRoutes = RouterModule.forRoot(appRoutes);
export const appRoutingProviders: any[] = [];
并注册为,
@NgModule({
declarations: [
// declarations
],
imports: [
AppRoutes
],
providers: [
appRoutingProviders
],
bootstrap: [AppComponent]
})
export class AppModule { }
因此该应用程序与 RouterLink 配合得很好
[routerLink]="['/user', username, 'detail']
但是当我浏览浏览器时 <host>/user/myuser/detail
它引发异常
Uncaught (in promise): Error: Cannot find primary outlet to load 'DetailComponent'
怎么了?谢谢。
注意:我已经设置了 <router-outlet>
并且在 routerLink 上完美运行,当在浏览器中浏览完整 url 时出现问题。
最佳答案
我假设当您从 user/:username/
导航到 /user/:username/detail
时,您需要 UserComponent
隐藏他模板上的所有内容并显示 DetailComponent
因此,要实现这一点,您需要一个组件来加载其子组件:
parent.component.html
<router-outlet></router-outlet>
routes.ts
现在让我们设置路由,以便user/:username/
将在父组件中加载
// user routes
export const userRoutes : Routes = [
{
path: '',
component: UserComponent // the '' path will load UserComponent
},
{
path: 'detail',
component: DetailComponent
},
{
path: 'friends',
component: FriendsComponent
},
{
path: 'profile',
component: ProfileComponent
}
]
//app routes
const appRoutes: Routes = [
{
path: '',
component: HomeComponent
},
{
path: 'photos',
component: PhotosComponent
},
{
path: 'posts',
component: PostsComponent
},
{
path: 'users',
component: UserListComponent
},
{
path: 'user/:username',
component: ParentComponent, //This component will load its children
children: userRoutes
},
{
path: 'videos',
component: VideosComponent
}
]
export const AppRoutes = RouterModule.forRoot(appRoutes);
export const appRoutingProviders: any[] = [];
所以,这里发生的事情是,当您导航到 user/:username
时,ParentComponent
被加载,然后 UserComponent
被加载到父组件的导出(因为 ''
路径对应于 user/:username
)
这是一个工作示例: Github
当您访问 user/myuser
时,它将显示:user works !
user/myuser/details
将显示:详细信息有效!正如您在下面看到的(不使用路由器链接)
关于通过浏览器 URL 导航时 Angular 2 路由不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42809363/