作为新手,我在 Angular 2 中设置路由时遇到问题。 虽然我很确定,但这是我所缺少的非常基本的东西。
我只想让我的 App Component
加载并显示标题。在它的正下方,一个链接将加载路由器 socket 部分中的 contact-list 组件
。
import { Component,OnInit } from '@angular/core';
import { Contact } from './contact';
@Component({
selector: 'app-root',
template: `
<h1>{{title}}</h1>
<a routerLink="/contact-list">Contact List</a>
<router-outlet></router-outlet>
`
})
export class AppComponent{
title = 'Welcome to my Dream App!';
}
这是 app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { RouterModule } from '@angular/router';
import { AppComponent } from './app.component';
import { ContactCardComponent } from './contact-card.component';
import { ContactsListComponent } from './contacts-list.component';
RouterModule.forRoot([
{
path:'',
redirectTo:'app',
pathMatch:'full',
},
{
path:'app',
component:AppComponent
},
{
path:'contact-list',
component:ContactsListComponent
},
{
path:'contact-details/:id',
component:ContactCardComponent
}
]);
@NgModule({
declarations: [
AppComponent,
ContactsListComponent,
ContactCardComponent
],
imports: [
BrowserModule,
FormsModule,
HttpModule,
RouterModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
但是是说:
error_handler.js:54 异常:./AppComponent 类 AppComponent 中的错误 - 内联模板:2:4 由:没有路由器提供程序引起!
没有路由器提供者。
我做错了什么?
更新:
如果我这样做:
template: `
<h1>{{title}}</h1>
<contacts-list></contacts-list>
`
在 app.component.ts
中,它工作正常。
发布解决方案后,我看到重复的行:
最佳答案
您应该将 RouterModule 导入到您的模块定义和“导入”数组中:
const ROUTES = [
// HERE ROUTES DEFINITIONS
]
@NgModule({
imports: [
RouterModule.forChild(ROUTES)
],
declarations: [],
providers: []
})
export default class YourModuleDefinition{
}
所以你的代码应该是这样的:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { RouterModule } from '@angular/router';
import { AppComponent } from './app.component';
import { ContactCardComponent } from './contact-card.component';
import { ContactsListComponent } from './contacts-list.component';
@NgModule({
declarations: [
AppComponent,
ContactsListComponent,
ContactCardComponent
],
imports: [
BrowserModule,
FormsModule,
HttpModule,
RouterModule.forRoot([
{
path:'',
redirectTo:'app',
pathMatch:'full',
},
{
path:'app',
component:AppComponent
},
{
path:'contact-list',
component:ContactsListComponent
},
{
path:'contact-details/:id',
component:ContactCardComponent
}
]);
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
具有提供的配置并添加到导入数组的 RouterModule 的 forRoot 静态类方法提供模块的路由问题。
关于javascript - Angular 2中没有路由器提供者,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46111428/