Angular4:编译失败:参数类型{path:string,component HomeComponent} []不能分配给参数类型Routes

时间:2017-06-21 10:33:30

标签: angular angular-routing

我正试图在Angular 4上首次设置路由:

enter image description here

我的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'不能分配类型'输入'。

2 个答案:

答案 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)

  

仅供参考

在组件类中进行更改后,我收到此错误 enter image description here

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:

REFERENCE LINK