Angular 2路由器错误:路由的配置无效' undefined'

时间:2016-07-26 17:08:03

标签: angular angular2-routing

我正在使用Angular 2路由器3.0.0-beta.2。

似乎无法让单一路线发挥作用。

"错误:路线配置无效'未定义':组件,redirectTo,必须提供儿童"

main.ts

import { bootstrap } from '@angular/platform-browser-dynamic';
import { enableProdMode } from '@angular/core';
import { AppComponent, environment, appRouterProviders } from './app';

bootstrap(AppComponent, [appRouterProviders])
  .catch(err => console.error(err));

app.routes.ts

import {provideRouter, RouterConfig}  from '@angular/router';
import {HomeComponent} from './';

export const appRoutes:RouterConfig = [
  [{
    path: '',
    redirectTo: '/home',
    pathMatch: 'full'
  },{
     path: 'home',
     component: HomeComponent
  }]
];

export const routes: RouterConfig = [
  ...appRoutes
];

export const appRouterProviders = [
  provideRouter(routes)
];

app.component.ts

import { Component } from '@angular/core';
import { ROUTER_DIRECTIVES }  from '@angular/router';

 @Component({
  moduleId: module.id,
  selector: 'app-root',
  templateUrl: 'app.component.html',
  directives: [ROUTER_DIRECTIVES]
})
export class AppComponent {
  title = 'app works!';
}

home.component.ts

import { Component, OnInit } from '@angular/core';
import { ROUTER_DIRECTIVES }    from '@angular/router';

@Component({
  moduleId: module.id,
  selector: 'app-home',
  templateUrl: 'home.component.html',
  directives: [ROUTER_DIRECTIVES]
})
export class HomeComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }

}

app.component.html

<h1>
  App Shell
</h1>
<router-outlet></router-outlet>

3 个答案:

答案 0 :(得分:9)

您需要为 HomeComponent 导入提供正确的相对路径:

而不是:

import {HomeComponent} from './';

这样做:

import {HomeComponent} from './home.component';

<强> app.routes.ts

import {provideRouter, RouterConfig}  from '@angular/router';
import {HomeComponent} from './home.component';  // you need to provide correct relative path

const appRoutes:RouterConfig = [                 //removed export
      {                                          // removed square bracket
        path: '',
        redirectTo: '/home',
        pathMatch: 'full'
      },{
         path: 'home',
         component: HomeComponent
      }
    ];


    export const appRouterProviders = [
      provideRouter(routes)
    ];

<强> main.ts

import { bootstrap } from '@angular/platform-browser-dynamic';
import { enableProdMode } from '@angular/core';
import { AppComponent} from './app.component';     //please provide right path
import {appRouterProviders } from './app.routes';  // added 

bootstrap(AppComponent, [appRouterProviders])
  .catch(err => console.error(err));

答案 1 :(得分:4)

对于将来的读者:

如果所涉及的组件未在模块上注册,并且可能造成混乱,也会显示此错误。

答案 2 :(得分:2)

就我而言,我忘了从默认路线中删除组件

{ path: '', redirectTo: '/home', component: MovieComponent, pathMatch: 'full' },
{ path: 'home', component: MovieComponent }

只需从第一行

中删除组件:MovieComponent 即可