router-outlet不是已知的元素

Mat*_*t S 17 angular2-routing

以下代码有效:

/*app.module.ts*/
import { NgModule } from '@angular/core';
import { HttpModule } from '@angular/http';
import { AppComponent } from './app.component';
import { LetterRecall } from './letterRecall/letterRecall.component';

@NgModule({
    imports:      [BrowserModule, HttpModule],
    declarations: [AppComponent, LetterRecall],
    bootstrap:    [AppComponent],
})
export class AppModule {}

/*app.component.ts*/
import {Component} from '@angular/core';
@Component({
    selector: 'my-app',
    templateUrl: 'app/app.component.html'
})
export class AppComponent { }

/*app.component.html*/
<h3>Title</h3>
<letter-recall></letter-recall>
Run Code Online (Sandbox Code Playgroud)

遵循Angular Routing Tutorial:https://angular.io/docs/ts/latest/tutorial/toh-pt5.html

我将我的代码修改为:

/*index.html*/
<head>
   <base href="/">

/*app.module.ts*/
import { NgModule } from '@angular/core';
import { HttpModule } from '@angular/http';
import { RouterModule } from '@angular/router';
import { AppComponent } from './app.component';
import { LetterRecall } from './letterRecall/letterRecall.component';

@NgModule({
    imports:      [BrowserModule, 
                   HttpModule,
                   RouterModule.forRoot([
                       { path: 'letters', component: LetterRecall }
                   ])],
    declarations: [AppComponent, LetterRecall],
    bootstrap:    [AppComponent],
})
export class AppModule {}

/*app.component.ts*/
import {Component} from '@angular/core';
@Component({
    selector: 'my-app',
    templateUrl: 'app/app.component.html'
})
export class AppComponent { }

/*app.component.html*/
<h3>Title</h3>
<a routerLink="/letters">Letters</a>
<router-outlet></router-outlet>
Run Code Online (Sandbox Code Playgroud)

此时我收到以下错误:

"未处理的承诺拒绝:模板解析错误:'router-outlet'不是已知元素:1.如果'router-outlet'是Angular组件,则验证它是该模块的一部分......"

我使用以下版本:

    "@angular/common": "2.4.0",
    "@angular/compiler": "2.4.0",
    "@angular/core": "2.4.0",
    "@angular/forms": "2.4.0",
    "@angular/http": "2.4.0",
    "@angular/platform-browser": "2.4.0",
    "@angular/platform-browser-dynamic": "2.4.0",
    "@angular/router": "3.4.0"
Run Code Online (Sandbox Code Playgroud)

SO上的所有其他答案表明我需要导入RouterModule,但正如您在上面看到的那样,我按照教程中的规定执行此操作.

有关我可以在哪里查找此错误来源的任何建议?我开始在PluralSight上使用John Papa的First Look教程,但看起来代码现在有点旧了.那时候我把所有这些都剥掉了,然后通过教程进行了简单的讨论,我得到了这个错误...我不确定下一步该转向何处.

Ger*_*ard 21

就像Erion说:在我的情况下,我在app.component.spec.ts中做了(添加)两件事:

import { RouterTestingModule } from '@angular/router/testing';
...
TestBed.configureTestingModule({ 
  imports: [ RouterTestingModule ],
  declarations: [
    AppComponent
  ],
}).compileComponents();
Run Code Online (Sandbox Code Playgroud)


小智 5

可能我来晚了,但是因为我遇到了同样的问题并在这里找到了答案。

你在使用 angular-cli 吗? https://github.com/angular/angular-cli/pull/3252/files#diff-badc0de0550cb14f40374a6074eb2a8b

就我而言,我只需要在 app.component.spec.ts 中导入我的新路由器模块 js 导入和 NgModule 导入。

然后重启测试服务器。