错误:无法匹配任何路线:''在Angular 2 RC5中使用Angular CLI

时间:2016-08-17 13:29:46

标签: angular angular2-routing angular-cli

我使用Angular 2 RC5开发了一个简单的应用程序。它只是渲染一个搜索页面,允许您单击一个记录进行编辑。简单的东西。我使用最新版本的Angular CLI从其主分支生成应用程序。由于此版本不支持路由,因此我必须使用router guide创建自己的版本。

不幸的是,当初始页面加载时,我在控制台中看到以下错误。

Error: Cannot match any routes: '''

这是我的app.routes.ts文件的样子:

import { Routes, RouterModule } from '@angular/router';
import { SearchComponent } from "./search/index";
import { EditComponent } from "./edit/index";
import { AppComponent } from "./app.component";

const appRoutes: Routes = [
    { path: 'search', component: SearchComponent },
    { path: 'edit/:id', component: EditComponent }
];

export const appRoutingProviders: any[] = [];

export const routing = RouterModule.forRoot(appRoutes);

然后在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 { routing, appRoutingProviders } from './app.routing';

import { AppComponent } from './app.component';
import { SearchComponent } from './search/search.component';
import { EditComponent } from './edit/edit.component';

@NgModule({
  declarations: [
    AppComponent,
    SearchComponent,
    EditComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    routing
  ],
  providers: [appRoutingProviders],
  entryComponents: [AppComponent],
  bootstrap: [AppComponent]
})
export class AppModule { }

我尝试为''添加路径。在app.routing.ts中,但这导致我的网页呈现AppComponent两次:

const appRoutes: Routes = [
  { path: 'search', component: SearchComponent },
  { path: 'edit/:id', component: EditComponent },
  { path: '', component: AppComponent }
];

index.html中,有HTML加载AppComponent

<app-root>Loading...</app-root>

app.component.html中,我有一个路由器插座来加载页面。

<!-- Routed views go here -->
<router-outlet></router-outlet>

3 个答案:

答案 0 :(得分:0)

定义您的路线:

const appRoutes: Routes = [
  { path: 'search', component: SearchComponent },
  { path: 'edit/:id', component: EditComponent },
  { path: '', redirectTo: '/search', pathMatch: 'full' }
];

请参阅官方文档:https://angular.io/docs/ts/latest/guide/router.html

有几个代码片段和掠夺者。

答案 1 :(得分:0)

app.module.ts中添加黄色区域 它的工作对我来说!我希望它有效!

答案 2 :(得分:0)

路线:

const routes: Routes = [
  { path: '', component: HeaderComponent },
  { path: 'dashboard',  component: DashboardComponent },
  { path: 'detail/:id', component: HeroDetailComponent },
  { path: 'heroes',     component: HeroesComponent }
];

应用组件应该只有:

<router-outlet></router-outlet>