2017-01-16 58 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 : '/' } ], 
...