Angular 4:RouterLink元素无法正常工作

我已将AppRoutingModule放在AppModule类的@NgModule导入中.

AppRoutingModule以这样的方式定义:

const APP_ROUTES : Routes = [
    { 
        path: '', 
        redirectTo: 'home', 
        pathMatch: 'full',
    },
    {
        path: 'home', 
        component: HomeComponent
    },
    {
        path: 'lesson-offers', 
        component: LessonOffersComponent
    },

    { path: '**', redirectTo: 'home' }
]

我已经放置了< router-outlet>< / router-outlet>在app.component.html中.

页面根据URL正确显示:

localhost:5000/  
localhost:5000/home  
localhost:5000/lesson-offers

问题出在我的header.component.ts中,我试图将routerLink添加到主页.我尝试过这样的解决方案:

<img routerLink="home" ... />
<img [routerLink]="/home" ... />
<a routerLink="home"> <img ... /></a>
<a [routerLink]="home" ... ><img ... /></a>

首先,当我将routerLink放入< img>元素此类指令尚未找到.然后在< a>中.它使休闲< a href =“/ home”>来自routerLink并进行全页重新加载!它不应该仅重新加载< router-outlet>的内容吗?

也许它有一些含义,我的布局看起来像这样:

// AppComponent HTML
<header-bar></header-bar>
<router-outlet></router-outlet>

和routerLink放在子组件< header-bar>中的元素上. (徽标)并应在< router-outlet>上导航在其父母?

但我也使用直接放在AppComonent中的routerLinks测试了这种行为,没有任何改变! RouterLink仍在重新加载网页!:

<header-bar></header-bar>
<a routerLink="home">Home</a> 
<a routerLink="lesson-offers">Lesson Offers</a>
<a routerLink="page-not-found">Not Exsists</a>
<router-outlet></router-outlet>

最佳答案 您需要更多工作才能使路由工作.以下是AppRoutingModule文件的外观

import { RouterModule, Routes } from '@angular/router';
import { NgModule } from '@angular/core';
import { HomeComponent, LessonOffersComponent } from somewhere;

const APP_ROUTES : Routes = [
    { 
        path: '', 
        redirectTo: 'home', 
        pathMatch: 'full',
    },
    {
        path: 'home', 
        component: HomeComponent
    },
    {
        path: 'lesson-offers', 
        component: LessonOffersComponent
    },

    { path: '**', redirectTo: 'home' }
]

@NgModule({
  imports: [ RouterModule.forRoot(APP_ROUTES) ],
  exports: [ RouterModule ]
})
export class AppRoutingModule {}
点赞