我一直在搞乱Angular 2而陷入困境 . 首页包含要学习的主题列表(TopicsComponent) . 点击它们将触发路径:'**' . PageNotFoundComponent也使用TopicsComponent来显示主题,但routerLink不再工作 .
示例:在首页,当我单击angular2链接时,我得到url /angular2 . 但是当PageNotFoundComponent处于活动状态时,我会得到url /angular2/(angular2)
这是代码:
main.ts
import { bootstrap } from '@angular/platform-browser-dynamic';
import { appRouterProviders } from './app.routes';
import { AppComponent } from './app.component';
bootstrap(AppComponent, [appRouterProviders]);
app.routes.ts
import { provideRouter, RouterConfig } from '@angular/router';
import { TopicsComponent } from './topics/topics.component';
import { PageNotFoundComponent } from './notfound/page-not-found.component';
const routes: RouterConfig = [
{
path: '',
component: TopicsComponent
},
{
path: '**',
component: PageNotFoundComponent
}
];
export const appRouterProviders = [
provideRouter(routes)
];
app.component.ts
import { Component } from '@angular/core';
import { ROUTER_DIRECTIVES } from '@angular/router';
import { TopicsService } from './shared/topics.service';
import { TopicsComponent } from './topics/topics.component';
import { PageNotFoundComponent } from './notfound/page-not-found.component';
@Component({
selector: 'my-app',
templateUrl: 'app/app.component.html',
directives: [ROUTER_DIRECTIVES],
providers: [KoodikoguService],
precompile: [TopicsComponent, PageNotFoundComponent]
})
export class AppComponent { }
topics.component.ts
import { Component, OnInit } from '@angular/core';
import { ROUTER_DIRECTIVES } from '@angular/router';
import { TopicsService } from './shared/topics.service';
@Component({
selector: 'topics',
templateUrl: 'app/topics/topics.component.html',
directives: [ROUTER_DIRECTIVES]
})
export class TopicsComponent {
title = 'Welcome to the topics component!';
topics:any;
constructor(private _dataService: TopicsService) {
}
ngOnInit() {
this._dataService.getTopics().then(topics => this.topics = topics);
}
}
topics.component.html
<h1>{{ title }}</h1>
<div *ngFor="let topic of topics">
<a [routerLink]="topic.title" routerLinkActive="active">{{ topic.title }}</a>
</div>
page-not-found.component.ts
import { Component } from '@angular/core';
import { ROUTER_DIRECTIVES } from '@angular/router';
import { TopicsComponent } from '../topics/topics.component';
@Component({
selector: 'not-found',
templateUrl: 'app/notfound/page-not-found.component.html',
directives: [TopicsComponent]
})
export class PageNotFoundComponent { }
page-not-found.component.ts
<h1>Page not found!</h1>
<topics></topics>
2 回答
像这样的URL:'/ angular2 /(angular2)'用于表示两个不同的RouterOutlets的路径,parens外的默认出口,以及parens内的辅助/辅助出口 . 不知道为什么会在你的代码中发生这种情况,因为我没有看到任何RouterOutlets . 你能举一个关于Plunker(或其他一些让你做Angular2示例应用程序的网站)的例子吗?
尝试将pathMatch添加到默认路由,并确保您的html文件具有基本href'/'而不是' . '如果这是使用 .