Angular - Combine params and queryParams observabl

2019-04-12 09:48发布

How can I combine these to observables into one? They have the same functionality.

this.sub = this.route.params.subscribe((params: any) => {
    // functionality
});

this.sub = this.route.queryParams.subscribe((params: any) => {
    // same functionality   
});

1条回答
Lonely孤独者°
2楼-- · 2019-04-12 10:28

You can use combineLatest to do that:

import { ActivatedRoute } from '@angular/router';

import { combineLatest } from 'rxjs';

// ...

class MyComponent {

  constructor(private route: ActivatedRoute) { }

  ngOnInit() {

    const params = this.route.params;
    const queryParams = this.route.queryParams;

    combineLatest(params, queryParams, (params, qparams) => ({ params, qparams }))
      .subscribe(allParams => console.log(allParams.params, allParams.qparams));
  }

}

params and qparams will be objects with the property name as the param name and the value as the value. So for a route:

 RouterModule.forRoot([{
  path: 'test1/:id',
  component: Test1Component
}])

with params

http://localhost:4200/test1/paramvalue?qparam=qpvalue

allParams will be

{ 
  params: { 
     id: "paramvalue" 
    },
  qparams: { 
     qparam: "qpvalue" 
    } 
 }
查看更多
登录 后发表回答