4

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   
});
Michalis
  • 6,686
  • 13
  • 52
  • 78

1 Answers1

7

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" 
    } 
 }
Machado
  • 8,965
  • 6
  • 43
  • 46
JayChase
  • 11,174
  • 2
  • 43
  • 52
  • allParams ahve inside 2 objects "params" and "qparams". Params is ok but qparams has params: "[object Object]" and qparams: "[object Object]" and all the other actual params – Michalis Aug 02 '17 at 04:33
  • @Michalis I added some more detail to the answer both the params properties will be objects. – JayChase Aug 02 '17 at 05:06
  • did you see the screenshot? – Michalis Aug 02 '17 at 05:36
  • I don't get the same results. I'm on Angular 4.3.1. – JayChase Aug 02 '17 at 06:02
  • I'm using the default router configuration. I'm not sure whether anything on that side could make the ActivatedRoute different. – JayChase Aug 02 '17 at 06:13
  • import { Observable } from 'rxjs/Rx'; Need add import statment to work with Observable object. – mahesh kajale Jun 06 '18 at 05:05
  • 1
    @maheshkajale That will import everything. To just import Observable if you are using < version 6 use `import { Observable } from 'rxjs/Observable';` – JayChase Jun 06 '18 at 08:10
  • 2
    It works fine except one case that change url from http://localhost:4200/test1/paramvalue?qparam=qpvalue to http://localhost:4200/test1/otherParamValue. At that time combineLatest run twice one for query param and other for path param. How can we solve this problem? – mai danh Jan 20 '19 at 15:54