2017-01-16 57 views
2

我正在关注的Angular2教程:Tour of HeroesAngular2 - 问题与:RouterModule.forRoot

我所有的教程之旅已不如预期,但是当到达处如下:

https://angular.io/docs/ts/latest/tutorial/toh-pt5.html#!#add-a-dashboard-

它不是应该如此。

它假设要与工作:

1-上的文件: “app.module.ts”,在取消代码:RouterModule.forRoot...

2-上的文件: “app.component.ts”,添加以下行到模板:

<a routerLink="/heroes">Heroes</a> 
<router-outlet></router-outlet> 

我知道我应该提供最小化的代码,但我认为这是不可能的我,因为我不知道到底是哪里的问题。我能说的是,我一直在按照教程一步一步地工作。

在这里你有,你可以下载到这个点源:

https://github.com/nightclubso/project_03

像它现在它正在发挥作用。没有编译问题。但是如果你在浏览器控制台上面做了2点,那么你会发现很多错误。

必须修改(如教程建议)的文件包括:具有终于

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'; 


@NgModule({ 
    imports:  [ 
    BrowserModule, 
    FormsModule, 
    RouterModule.forRoot([ 
     { 
     path: 'heroes', 
     component: HeroesComponent 
     } 
    ]) 
    ], 
    declarations: [ 
    AppComponent, 
    HeroDetailComponent, 
    HeroesComponent, 
    ], 
    providers: [ HeroService ], 
    bootstrap: [ AppComponent ] 
}) 
export class AppModule { } 

app.component.ts其最终下面的代码:

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

@Component ({ 
    selector: "my-app", 
    template: ` 
     <h1>{{title}}</h1> 
     <a routerLink="/heroes">Heroes</a> 
     <router-outlet></router-outlet> 
    `, 
}) 
export class AppComponent { 
    title: string = "Tour of Heroes"; 
} 

但由于某种原因,它不显示任何东西。

关于如何解决这个问题的任何想法?

+0

请您在控制台上有错误,至少共享屏幕。 – VadimB

+0

什么'它不工作,因为它应该。预期的行为是什么,实际的行为是什么? –

+0

尝试添加'{path:'',redirectTo:'/ heroes',pathMatch:'full'}'作为第一条路线 –

回答

0

您刚刚在您的应用中配置了routes。因为configured routesrouter-outlet,你什么都没有(作为输出)。所以,在这里,你需要明确提供您的路由配置,如下图所示,

RouterModule.forRoot([ 
    { 
    path: '', 
    redirectTo: '/heroes', 
    pathMatch: 'full' 
    }, 
    { 
    path: 'heroes', 
    component: HeroesComponent 
    } 
]) 
+0

我做到了这一点,但没有成功。在编译控制台(tsc)上没有错误。但在浏览器中,我收到了以下错误信息:https://raw.githubusercontent.com/nightclubso/project_03/master/issues/so_01.png。项目不会在浏览器上加载。我将我的更改提交到[GitHub存储库](https://github.com/nightclubso/project_03)。 – nightclub

0

恰好碰到了这个问题了。如果你看看错误信息,它说你需要为APP_BASE_HREF标记提供一个值或添加一个基本元素。所以你可以(推荐选项)打开索引。HTML文件,并添加

< base href = "/" > 

头元素给下:

... 
<head> 
    <base href="/"> 
    <title>Angular QuickStart</title> 
... 

OR

去你app.module.ts文件,其中有您的“供应商: ...“阵列,加

{provide: APP_BASE_HREF, useValue : "/" }

,并提供:

... 
providers: [ HeroService, {provide: APP_BASE_HREF, useValue : '/' } ], 
...