2017-02-26 137 views
2

我有幾個鏈接導航作爲Angular2路由器聽參數更改

http://localhost:4200/#/forward/services/our-services?category=1 
http://localhost:4200/#/forward/services/our-services?category=2 
http://localhost:4200/#/forward/services/our-services?category=3 

我想取

我用盡

this.sub = this._activatedRoute.params.subscribe(params => { 

    this.category = + params['category']; 

    console.log(params['category']); 

}); 

的執行console.log類的值()只是打一次,

我如何確保我捕獲每當類別的值更改

這是我使用的導航

<ul id="menu-services-menu" class="menu" *ngFor="let category of categories"> 
<li><a routerLinkActive="active" [routerLink]="['/forward/services/our-services']" [queryParams]="{ category: category.category }" >{{category.category}}</a></li> 

    </ul> 
+1

你想要的queryParams中的更改,而不是參數。 https://angular.io/docs/ts/latest/api/router/index/ActivatedRoute-interface.html#!#queryParams-anchor –

+0

真棒查詢參數工程 –

+0

即使參數發生變化,routerLinkActive類始終保持活動狀態 –

回答

2
constructor(router:Router, route:ActivatedRoute) { 
    router.events 
    filter(e => e instanceof NavigationEnd) 
    .forEach(e => console.log(route.snapshot.params['category']); 
} 
0

你也可以用角2(角5在本文寫作)做這樣的:

constructor(private router:Router) { 
router.events.subscribe(data=>{ 
    if(data instanceof ActivationEnd){ 
    this.category = data.snapshot.params['category']; 
    } 
}); 
} 
0
constructor(private route: ActivatedRoute, private router: Router) {} 

ngOnInit() { 
    this.route 
    .queryParams 
    .subscribe(params => { 
    this.page = params['category']; 
    }); 
} 
+0

您能否提供一些詞來解釋爲什麼這會有所幫助 – aholbreich

+0

當然,不是訂閱route.events,而是必須檢查或過濾事件,才能訂閱特定的queryParams並獲取參數。我認爲這個問題是一個更乾淨的解決方案。 – Dalcof