0

I am trying to subscribe to both route data and route params in Angular. I am using Observable.zip, but unfortunately subscribe function isn't trigger when I switch routes (I have routes A, B, C and D which has a parameter in URL).

My code looks as follows:

ngOnInit() {
    this.subscription = Observable.zip(this.route.data, this.route.params)
      .subscribe(([data, params]) => {
         // do something...
      });
  }

However, when I use these piece of code:

this.route.params.subscribe((data) => {
  // do something...
})

Everything works fine and I am able to subscribe to params. I want to do this using only one subscription.

TheOpti
  • 1,641
  • 3
  • 21
  • 38
  • Possible duplicate of [Subscribe to both route params and queryParams in Angular 2](https://stackoverflow.com/questions/40699229/subscribe-to-both-route-params-and-queryparams-in-angular-2) – JayChase Feb 16 '18 at 10:19

2 Answers2

6

The zip operator emits only when all source Observables emit the same number of items.

It looks like for you it'll be better to use combineLatest that emits after all source Observables emitted at least one item and then on every emission.

You can also append startWith and initialize combineLatest with nulls.

Observable.combineLatest(
  this.route.data.startWith(null),
  this.route.params.startWith(null),
  (data, params) => {
    ...
  }
).subscribe(...);
martin
  • 93,354
  • 25
  • 191
  • 226
1

You can do that with forkJoin , something like this :

const combined = Observable.forkJoin(
  this.route.data,
  this.route.params
)

combined.subscribe(latestValues => {
    const [ route_data , route_params ] = latestValues;
    console.log( "route_data" , route_data);
    console.log( "route_params" , route_params);
});
Vivek Doshi
  • 56,649
  • 12
  • 110
  • 122