gpt4 book ai didi

javascript - Angular 2 应用程序中的子路由

转载 作者:行者123 更新时间:2023-11-28 05:41:34 24 4
gpt4 key购买 nike


我尝试在我的 ng2-app 中实现子路由。启动应用程序后,我收到异常“组件“AppComponent”没有路由配置。”下面是我的代码:

ma​​in.ts:

import {bootstrap}    from '@angular/platform-browser-dynamic';
import {AppComponent} from './app.component';
import {FORM_PROVIDERS} from "@angular/forms";
import {HTTP_PROVIDERS} from "@angular/http";
import {AuthenticationService} from "./authentication/authentication.service";
import {provideRouter} from "@angular/router";
import {routes} from "./app.routes";
import {ROUTER_PROVIDERS} from "@angular/router-deprecated";

bootstrap(AppComponent, [
provideRouter(routes),
ROUTER_PROVIDERS,
FORM_PROVIDERS,
HTTP_PROVIDERS,
AuthenticationService
]);

app.routes.ts:

export const routes:RouterConfig = [
{path: '', component: HomeComponent, canActivate: [AuthenticationService]},
{path: 'login', component: LoginComponent},
{path: 'signup', component: SignupComponent},
{path: 'home', component: HomeComponent, canActivate: [AuthenticationService], children: [
{path: 'first-component', component: FirstComponent},
{path: 'second-component', component: SecondComponent}
]},
{path: '**', component: HomeComponent, canActivate: [AuthenticationService]}
];

app.component.ts:

import {Component} from '@angular/core';
import {ROUTER_DIRECTIVES, Router} from '@angular/router';
@Component({
selector: 'my-app',
template: `
<router-outlet></router-outlet>
`,
directives: [ROUTER_DIRECTIVES]
})

export class AppComponent {
constructor(public router:Router) {
}
}

home.component.ts:

import {Component} from "@angular/core";
import {SidebarComponent} from "./sidebar/sidebar.component";
import {HeaderComponent} from "./header/header.component";
import {ROUTER_DIRECTIVES} from "@angular/router-deprecated";
import {Router} from "@angular/router";
@Component({
selector: 'trinjer-home',
template: `
<header></header>
<sidebar></sidebar>
<router-outlet></router-outlet>
`,
directives: [SidebarComponent, HeaderComponent, ROUTER_DIRECTIVES]
})
export class HomeComponent {
constructor(private router: Router) {
}
}

不明白,我做错了什么,如何在 home.component 中配置这个子路由?
谢谢!

最佳答案

您必须通过将路径设置为空字符串来将其中一个子组件设置为父组件的默认组件

{path: 'home', component: HomeComponent, canActivate: [AuthenticationService], children: [
{path: '', redirectTo: 'first-component',
{path: 'first-component', component: FirstComponent},
{path: 'second-component', component: SecondComponent}
]},

从官方文档中查看

https://angular.io/docs/ts/latest/guide/router.html

另请查看本教程,它可能会帮助您更好地理解它

http://angular-2-training-book.rangle.io/handout/routing/child_routes.html

关于javascript - Angular 2 应用程序中的子路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38875592/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com