簡體   English   中英

Angular2-問題與:RouterModule.forRoot

[英]Angular2 - Issue with: RouterModule.forRoot

我正在關注Angular2教程: 英雄之旅

我的所有教程旅程都按預期進行,但是到達以下幾點:

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

就像現在一樣,它正在工作。 沒有編譯問題。 但是,如果您按照上述兩點進行操作,則在瀏覽器控制台上會看到很多錯誤。

您必須修改的文件(如本教程所建議)是:

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";
}

但由於某種原因,它什么也不顯示。

關於如何解決這個問題的任何想法?

您剛剛在應用程序中配置了routes 因此,由於configured routesrouter-outlet ,您一無所獲(作為輸出)。 因此,在這里您需要顯式提供路由配置,如下所示,

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

剛遇到這個問題。 如果查看錯誤消息,則表明您需要為APP_BASE_HREF令牌提供一個值或添加一個基本元素。 因此,您可以(推薦選項)打開index.html文件並添加

< base href = "/" >

在head元素下面給出:

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

要么

轉到您的app.module.ts文件,然后在您的“ providers:...”數組中添加

{provide: APP_BASE_HREF, useValue : "/" }

贈送:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM