我一直在搞Angular 2並陷入困境。首頁列出了要學習的主題(TopicsComponent)。單擊它們將觸發路徑:現在爲'**'。 PageNotFoundComponent也使用TopicsComponent來顯示主題,但routerLink不再工作。Angular2 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>
頁面 - 不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 { }
頁面未found.component.ts
<h1>Page not found!</h1>
<topics></topics>
'topic.title'的價值是什麼? –
topic.title ='angular2' – EstSiim
嘗試'[routerLink] =「'/'+ topic.title」 –