angular 2 pathMatch路由不起作用

时间:2016-12-20 13:21:52

标签: angular angular2-routing

我尝试传递angular2 heroes-tour

我遇到了路由部分的问题。

项目结构:

enter image description here

在编写的教程中,如果写在模板中:

app.component.html:

<h1>{{title}}</h1>
<nav>
    <a routerLink="/dashboard">Dashboard</a>
    <a routerLink="/heroes">Heroes</a>
</nav>
<router-outlet></router-outlet>

并像这样配置路由:

app.module.ts:

import { NgModule }       from '@angular/core';
import { BrowserModule }  from '@angular/platform-browser';
import { FormsModule }    from '@angular/forms';
import { RouterModule }   from '@angular/router';

import { AppComponent }        from './app.component';
import { HeroDetailComponent } from './hero-detail.component';
import { HeroesComponent }     from './heroes.component';
import { HeroService }         from './hero.service';
import {DashBoardComponent} from "./dashboard.component";

@NgModule({
    imports: [
        BrowserModule,
        FormsModule,
        RouterModule.forRoot([
            {
                path: 'heroes',
                component: HeroesComponent
            }, {
                path: 'dashboard',
                component: DashBoardComponent,
                pathMatch: 'full'
            }, {
                path: 'detail/:id',
                component: HeroDetailComponent
            },
        ])
    ],
    declarations: [
        AppComponent,
        HeroDetailComponent,
        HeroesComponent,
        DashBoardComponent
    ],
    providers: [
        HeroService
    ],
    bootstrap: [AppComponent]
})
export class AppModule {
}

然后

  

要在浏览器中查看这些更改,请转到应用程序根目录(/)   并重新加载。该应用程序显示仪表板,我们可以在其间导航   仪表板和英雄。

就我而言,我看到了:

enter image description here

因此,重新加载页面后,重定向到/仪表板不会发生。

我错了什么?

P.S。
请随时向我添加更多详细信息发布。

1 个答案:

答案 0 :(得分:2)

请记住,当您执行http://localhost:3000时,浏览器会在npm start网址上启动,但您的路由配置中的任何网址都不匹配,因此您需要在RouterModule.forRoot内添加以下重定向规则,以便应用它会在dashboard开始时显示,您可以在浏览器地址栏中看到一个名为/dashboard的网址:

{
  path: '',
  redirectTo: '/dashboard',
  pathMatch: 'full'
}