Do we need RXJS combineLatest with ActivateRouted.pathFromRoot?

Viewed 121

The Angular Material Documentation application retrieves route parameters from lazy loaded route modules like this:

https://github.com/angular/material.angular.io/blob/master/src/app/pages/component-category-list/component-category-list.ts

// Combine params from all of the path into a single object.
    this.params = combineLatest(
        this._route.pathFromRoot.map(route => route.params), Object.assign);

It seems like we don't really need combineLatest for this?

The _route is constructor injected and IIUC once the component has the reference to it the pathFromRoot array of ActivateRoute instance cannot change?

Since that's the case we don't need combineLatest?

So it seems like we could do something like this instead:

const paramArr = this._route.pathFromRoot.map(route => route.params)

this.params = of(Object.assign(paramArr))

Does this make sense?

2 Answers

In

const paramArr = this._route.pathFromRoot.map(route => route.params)

pathFromRoute and therefore route won't change. But route.params is an Observable and this Observable can emit new values over time. To get notified when one of those Observables emits a new value you have to subscribe to all of those Observables. That's why combineLatest is used.


this.params = of(Object.assign(paramArr))

Isn't really helpful. It creates an Observable that emits an array of Observables so you'd have to flatten this Observable in another step. When you use combineLatest you won't need this extra step.

It seems like we don't really need combineLatest for this?

I'd say it is needed, but it also depends on what you'd want to achieve.

For instance, with this approach:

const paramArr = this._route.pathFromRoot.map(route => route.params)

this.params = of(Object.assign(paramArr))

You'd get the params from the ActivatedRoute root to the current ActivatedRoute child only once. Meaning that if the params of a route gets updated(e.g first you navigate to /1, then to /2), you'd only get 1. Also, I'm not sure this would work as expected, since paramsArr will be an array of observables(ActivatedRoute.params is a BehaviorSubject AFAIK).

Whereas if you use this approach:

this.params = combineLatest(
        this._route.pathFromRoot.map(route => route.params), Object.assign);

You will be notified of all the params updates that occur in the ActivatedRoute tree, not only once, but every time.

I've elaborated on how ActivatedRoute works(among other things) in this article.

Related