【问题标题】:Angular2 - Issue with: RouterModule.forRootAngular2 - 问题:RouterModule.forRoot
【发布时间】:2017-01-16 08:55:52
【问题描述】:

我正在关注Angular2 教程:Tour of Heroes

我所有的教程之旅都如预期的那样,但是当到达以下点时:

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

但由于某种原因,它没有显示任何内容。

你知道如何解决这个问题吗?

【问题讨论】:

  • 请至少分享您在控制台上遇到的错误的屏幕。
  • It is not working as it should. 到底是什么意思。预期行为是什么,实际行为是什么?
  • 尝试添加{ path: '', redirectTo : '/heroes', pathMatch: 'full' }作为第一条路线

标签: javascript angular typescript


【解决方案1】:

您刚刚在您的应用中配置了routes。因此,由于 configured routesrouter-outlet,您什么也得不到(作为输出)。所以,这里你需要明确地提供你的路由配置,如下所示,

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

【讨论】:

【解决方案2】:

刚刚也遇到了这个问题。如果您查看错误消息,它表示您需要为 APP_BASE_HREF 令牌提供一个值或添加一个基本元素。因此,您可以(推荐选项)打开 index.html 文件并添加

< base href = "/" >

在head元素下给出:

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

转到您的 app.module.ts 文件,以及您的“提供者: ..." 数组,添加

{provide: APP_BASE_HREF, useValue : "/" }

给予:

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

【讨论】:

    猜你喜欢
    • 2017-05-18
    • 2016-05-11
    • 2017-02-01
    • 1970-01-01
    • 2017-03-22
    • 2016-10-18
    • 2016-05-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多