簡體   English   中英

如何匹配帶有angular2 rc5的APP MODULE TS中的任何路線?

[英]How to match any routes in APP MODULE TS with angular2 rc5?

我有一個簡單的angular應用程序,並且是第一次使用Angular2。

我在Firefox控制台中收到錯誤提示:“例外:未捕獲(承諾中):錯誤:無法匹配任何路由:'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時 ,沒有錯誤。 但是當我訪問http:// localhost:4200 / book / huckleberry時 ,第一次使用Angular2。

我在Firefox控制台中收到錯誤提示:“例外:未捕獲(承諾):錯誤:無法匹配任何路由:'book / huckleberry'”

您知道如何更新app.module.ts嗎?

我應該能夠在book.component.html中獲得{{book}}

我可以通過以下代碼解決此問題:

app.routes.ts const APP_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}}打印到頁面上

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM