2017-03-04 109 views
0

我試圖用參數實現基本路由,模仿英雄示例(https://angular.io/docs/ts/latest/guide/router.html)。我的AppModule聲明的路徑:Angular 2路由行爲不如預期

const appRoutes: Routes = [ 
    { path: '',  component: AllStuffComponent }, 
    { path: 'stuff/:id', component: SingleStuffComponent }, 
]; 

我SingleStuffComponent如下所示,只是爲了測試出來的力學:

export class SingleGuiComponent implements OnInit { 

    constructor(
    private route: ActivatedRoute, 
    private router: Router, 
) {} 

    ngOnInit() { 
    this.route.params 
     .switchMap((params: Params) => params['id']) 
     .subscribe((id: any) => console.info("ID=" + id)); 
    } 
} 

我試圖在http://localhost:3000/stuff/2345瀏覽器做了URL。但在調試器中,我看到:

ID=2 
ID=3 
ID=4 
ID=5 

這是爲什麼發生?我預計只有單一控制檯日誌ID=2345

+0

你有沒有嘗試刪除'switchMap'功能,並獲得了'PARAMS [ '身份證']在'subscribe'函數裏面? 我懷疑'switchMap'將字符串分割爲單個字符 –

回答

0

我想你應該嘗試只使用map()函數來提取ID,它會起作用。

this.route.params 
     .map((params: Params) => params['id']) 
     .subscribe((id: any) => console.info("ID=" + id)); 

您將主要使用switchMap()從地圖()獲取發射ID,並將其用於新的API調用或類似的東西,這樣你就不必窩2訂閱功能。

例子:

this.route.params 
     .map((params: Params) => params['id']) 
     .switchMap(id => this._someService.getSomething(id)) 
     .subscribe((result: any) => { 
      console.log(result); 
     }); 

沒有switchMap(),你就必須做:

this.route.params 
    .map((params: Params) => params['id']) 
    .subscribe((id) => { 
    this._someService 
     .getSomething(id) 
     .subscribe(result => this.result = result); 
    }); 
+0

是的!這工作。雖然,我很困惑爲什麼Angular的Hero例子(hero-details.component.ts)有switchMap()。 –