我有一个简单的角度应用程序,我第一次使用Angular2。
我在firefox控制台中出现错误“EXCEPTION:Uncaught(在承诺中):错误:无法匹配任何路线:'books / huckleberry'”
book.component.ts
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
@Component({
selector: 'app-directory',
templateUrl: './book.component.html',
styleUrls: ['./book.component.css']
})
export class BookComponent implements OnInit {
book: string;
constructor(private route: ActivatedRoute) {
this.book= route.snapshot.params['book'];
}
ngOnInit() {
}
}
app.routes.ts
import { Routes, RouterModule } from "@angular/router";
import { BookComponent } from "./book/book.component";
import { HomeComponent } from "./home/home.component";
const APP_ROUTES: Routes = [
{
path:'book',
component: BookComponent,
children: [
{ path: 'book/:book', component: BookComponent}
]
},
{ path: '', component: HomeComponent }
];
export const APP_ROUTES_PROVIDER = RouterModule.forRoot(APP_ROUTES);
app.module.ts
...
import { BookComponent } from './book/book.component';
import { RouterModule } from "@angular/router";
@NgModule({
declarations: [
AppComponent,
BookComponent,
HomeComponent,
],
imports: [
BrowserModule,
FormsModule,
HttpModule,
RouterModule.forRoot([
{ path: '', component: HomeComponent },
{ path: 'book', component: BookComponent },
// { path: '**', component: PageNotFoundComponent }
]),
RouterModule.forChild([
{
path: 'book', //parent path
children: [
{
path: 'book/:book',
component: BookComponent,
}
]
}
])
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
当我访问http://localhost:4200/book时,没有错误。 但是当我第一次使用Angular2时访问http://localhost:4200/book/huckleberry。
我在firefox控制台中提示错误“EXCEPTION:Uncaught(在承诺中):错误:无法匹配任何路由:'book / huckleberry'”
您知道我如何更新 app.module.ts ?
我应该能够在book.component.html
中获得{{book}}答案 0 :(得分:0)
我能够通过以下代码解决这个问题:
<强> app.routes.ts 强> const APP_ROUTES:Routes = [
{ path:'directory', component: BookComponent },
{ path:'directory/:book', component: BookComponent },
{ path: '', component: HomeComponent }
];
<强> app.module.ts 强>
@NgModule({
declarations: [
AppComponent,
DirectoryComponent,
HomeComponent,
],
imports: [
BrowserModule,
FormsModule,
HttpModule,
RouterModule.forRoot([
{ path: '', component: HomeComponent },
{ path: 'book', component: BookComponent },
{ path: 'book/:book', component: BookComponent }
// { path: '**', component: PageNotFoundComponent }
])
],
providers: [],
bootstrap: [AppComponent]
})
使用上面的代码,我现在可以通过{{book}}
获取参数并将其打印到页面