Angular2路由器监听参数更改

时间:2017-02-26 14:25:00

标签: angular typescript

我有几个链接导航为

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>

3 个答案:

答案 0 :(得分:4)

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

答案 1 :(得分:1)

您也可以使用Angular 2(撰写本文时的Angular 5)执行此操作:

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

答案 2 :(得分:0)

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

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