【问题标题】:angular 2 pathMatch routing doesn't workangular 2 pathMatch 路由不起作用
【发布时间】:2017-05-05 17:34:47
【问题描述】:

我尝试通过angular2 heroes-tour

我对路由部分有疑问。

项目结构:

在教程中如果写在模板中:

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 {
}

然后

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

就我而言,我看到了:

因此重新加载页面后不会发生重定向到 /dashboard。

我做错了什么?

附言
随时要求我添加更多详细信息以发布。

【问题讨论】:

  • 您检查控制台是否有任何错误?也许它找不到您的组件之一?
  • 你在app.module.ts中添加RouterModule了吗?
  • @Jaime Torres 控制台为空。如果点击链接 - 每个组件都可以正常打开
  • @Rumes Shyaman,是的,我添加了
  • 你可以添加整个路由代码吗?

标签: angular angular2-routing


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-09-20
    • 1970-01-01
    • 1970-01-01
    • 2017-03-03
    • 2018-12-24
    • 2017-04-06
    • 2017-01-01
    • 1970-01-01
    相关资源
    最近更新 更多