2016-09-25 51 views
0

能否告诉我为什么路由在Angular 2中不起作用?我尝试在路径为空时加载组件。为什么路由在Angular 2中不起作用?

这里是我的代码:

http://plnkr.co/edit/Vgc2bB7Lc8h9XsuhIg6X?p=preview

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


import { AppComponent } from './app.component'; 


const routes =[ 
    { 
    path :'' ,component:HomeComponent 
    } 
    ]; 


@Component({ 
    selector: 'home', 
    template: '<h1>home</h1>' 
}) 
export class HomeComponent { } 

@NgModule({ 
    imports:  [ BrowserModule,RouterModule.forRoot(routes)], 
    declarations: [ AppComponent,HomeComponent ], 
    bootstrap: [ AppComponent ] 
}) 

export class AppModule 
{ } 

回答

1

有一些问题与您的代码:

  1. base href需要进行设置,如解释here。通常情况下,这看起来像:
    <base href="/">
    为了让您的plunker工作,但是,你需要沿着线的东西:
    <script>document.write('<base href="' + document.location + '" />');</script>

  2. 您需要将HomeComponent的声明移到您在路由定义中使用它的位置之前。

更新的重击器here

0

检查您的控制台是否有错误,我认为没有基础href标记导致此错误。 引起:在index.html中没有设置基础href。请为APP_BASE_HREF标记提供值或向文档添加基本元素。

<script>document.write('<base href="' + document.location + '" />');</script> 

在你app.module.ts没有回家构成元素。

import { AppComponent } from './app.component'; 
import { HomeComponent } from './app.home-component'; 

const routes =[ 
    { 
    path :'' ,component:HomeComponent 
    } 
    ];