我正试图在Angular 4上首次设置路由:
我的app.module.ts代码:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';
import { AppComponent } from './app.component';
import { ProductComponent } from './product/product.component';
import { MembersComponent } from './members/members.component';
@NgModule({
declarations: [
AppComponent,
ProductComponent,
MembersComponent
],
imports: [
BrowserModule,
NgModule,
RouterModule.forRoot([
{
path: 'member',
component: 'MembersComponent'
},
{
path: 'product',
component: 'ProductComponent'
}
])
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
我收到错误:
类型的参数' {path:string; component:string; } []'不是 可分配给'路线[]'类型的参数。输入' {path:string; component:string; }'不能分配类型'路线'。 财产类型'组件'是不相容的。 输入' string'不能分配类型'输入'。
答案 0 :(得分:1)
路由的定义如下:
export interface Route {
path?: string;
component?: Type<any>;
其中Type
的定义如下:
export declare const Type: FunctionConstructor;
所以你必须在路由定义中指定对组件类(它是函数构造函数)的引用,而不是字符串:
component: 'MembersComponent' <---------- should be component class reference
所以导入MembersComponent
并按照这样说:
import { MembersComponent } from '...'
...
RouterModule.forRoot([
{
path: 'member',
component: MembersComponent
},
答案 1 :(得分:0)
仅供参考
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';
import { AppComponent } from './app.component';
import { ProductComponent } from './product/product.component';
import { MembersComponent } from './members/members.component';
@NgModule({
declarations: [
AppComponent,
ProductComponent,
MembersComponent
],
imports: [
BrowserModule,
NgModule,
RouterModule.forRoot([
{
path: 'member',
component: MembersComponent
},
{
path: 'product',
component: ProductComponent
}
])
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
<强> SOLUTION:强>