首页 文章

angular 2 pathMatch路由不起作用

提问于
浏览
0

我试着通过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 回答

  • 2

    请记住,当您执行 npm start 时,浏览器会在 http://localhost:3000 url处启动,这与您的路由配置中的任何URL都不匹配,因此您需要在 RouterModule.forRoot 中添加以下重定向规则,以便应用程序在启动时显示 dashboard 并且您可以在其中看到一个不错的URL浏览器地址栏,显示 /dashboard

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

相关问题