2017-01-15 179 views
1

我正在学习Angular2路由并尝试显示欢迎页面。 我的应用程序有Angular 2路由与主页

三页
  • 欢迎页面(这只是一个空白页面,只是链接到其他途径)
  • 首页 - 一些文本和说明
  • 待办事项列表页 - 待办事项列表

问题是我无法管理显示欢迎页面。它会自动加载主页并默认显示来自HomeComponent的内容。

如截图所示,我只想显示2个链接。我只想在点击时从Home/Todo加载内容。但默认情况下,它会转到localhost:xxx/Home并加载主页。

enter image description here

我试图设置如下AppComponent的'空白的路径,但它加载AppComponent两次,显示的链接两次。

{ path: '', component: AppComponent, pathMatch: 'full' }, 

app.module.ts

@NgModule({ 
    imports: [ 
     BrowserModule, 
     HttpModule, 
     RouterModule.forRoot([ 
      { path: 'home', component: HomeComponent }, 
      { path: 'todo', component: TodoListComponent }, 
      { path: '**', redirectTo: 'home', pathMatch: 'full' } 
     ]) 
    ], 
    declarations: [ 
     AppComponent, 
     HomeComponent, 
     TodoListComponent 
    ], 
    bootstrap: [AppComponent], 
}) 
export class AppModule { } 

app.component.ts

import { Component } from "@angular/core" 

@Component({ 
    moduleId: module.id, 
    selector: 'app', 
    template: ` 
    <div> 
     <nav class='navbar navbar-default'> 
      <div class='container-fluid'> 
       <a class='navbar-brand'>{{pageTitle}}</a> 
       <ul class='nav navbar-nav'> 
        <li><a [routerLink]="['/home']">Home</a></li> 
        <li><a [routerLink]="['/todo']">To Do</a></li> 
       </ul> 
      </div> 
     </nav>   
    </div> 
    <div class='container'> 
      <router-outlet></router-outlet> 
     </div> 
    ` 
}) 
export class AppComponent {  
} 

家/ home.component.ts

import { Component } from '@angular/core'; 

@Component({ 
    moduleId: module.id,  
    templateUrl: "home.component.html"  
}) 
export class HomeComponent { 
} 

家/ home.component.html

<h1>Hello from Home Component</h1> 
<h2>This is my first TODO App for Angular 2...</h2> 

回答

2

我认为正在显示HomeComponent的原因是因为当网址是/ home您<router-outlet></router-outlet>将改变底层组件与home。你也有这条线在你的app.module.ts

{ path: '**', redirectTo: 'home', pathMatch: 'full' }

,这意味着您的所有网址不匹配/home/todo会让你HomeComponent弹出的。您可以尝试删除重定向:

{ path: '**', redirectTo: 'home', pathMatch: 'full' } 或改为改为''(或新的PageNotFoundComponent)。

还要确保在页面加载时,菜单中没有任何项目(家庭或待办事项)被选中。

0

你需要删除此行 {路径: '**',redirectTo: '家',pathMatch: '全'}

你在上面行提的是

如果任何网址其他/ home或/ todo来请redirectTo到/ home。所以它总是显示首页。

所以你app.module.ts应该

@NgModule({ 
 
    imports: [ 
 
    BrowserModule, 
 
    RouterModule.forRoot([ 
 
     { path: 'home', component: HomeComponent }, 
 
     { path: 'todo', component: TodoListComponent }, 
 
     { path: '**', redirectTo: 'home', pathMatch: 'full' } 
 
    ]) 
 
    ], 
 
    declarations: [ 
 
    AppComponent, 
 
    HomeComponent, 
 
    TodoListComponent 
 
    ], 
 
    bootstrap: [AppComponent], 
 
}) 
 
export class AppModule { }

这将解决这个问题。我试图和它得到了固定 ScreenShot

检查下面的链接为在角2 http://www.angularinfo.com/routings/

使用路由