angular icon indicating copy to clipboard operation
angular copied to clipboard

feat(router) add possibilty to subscribe to current ActivatedRoute

Open choeller opened this issue 10 years ago • 25 comments

I'm submitting a ... (check one with "x")

[ ] bug report
[x ] feature request
[ ] support request => Please do not submit support request here, instead see https://github.com/angular/angular/blob/master/CONTRIBUTING.md#question

Current behavior

Since #9390 is implemented we are now able to add a data-Object to the RouteConfig. This object is attached to the ActivatedRoute. As of now, I currently can't seem to find a way to globally subscribe to that ActivatedRoute to implement some generic functionallity like setting the browser title.

Expected/desired behavior

It would be super useful to be able to subscribe to the current ActivatedRoute or at least to be able to get this information ad-hoc from the router (via snapshot?!). Something like this would be quite nice:

    router.activatedRoute.subscribe((route: ActivatedRouteSnapshot) => {
      if (route.outlet == PRIMARY_OUTLET) {
        this.titleService.setTitle(route.data['title'] || "My default title");
      }
    })

What is the motivation / use case for changing the behavior?

Be able to solve generic routing issues by accessing information about the current route.

Please tell us about your environment:

  • Angular version: 2.0.0-rc.3
  • Browser: [all]
  • Language: [all ]

choeller avatar Jun 28 '16 08:06 choeller

The RouterState is a tree if ActivatedRoutes, so its already possible to get what you need although its not easy as what you've requested. You can subscribe to router events and map that to the routerState and to get the first activated route.

http://plnkr.co/edit/pHd89K?p=preview

brandonroberts avatar Jun 28 '16 12:06 brandonroberts

Thanks a lot for that trick @brandonroberts . I had to do some little changes for it to support child-routes, so if anyone is interested here is what I did:

http://plnkr.co/edit/rn5qh6?p=preview

choeller avatar Jun 28 '16 14:06 choeller

@brandonroberts Hi, may you explain, please, how data observable prop shows up at the route? I try to do the same trick in my app, but data prop doesn't shows up...

Niaro avatar Jun 29 '16 10:06 Niaro

@Niaro the data-field is not released yet. The plnkr uses the current master of angular. So if you want to use it in your app you currently need to build angular on your own.

choeller avatar Jun 29 '16 11:06 choeller

@choeller Okay...( Thank you)

Niaro avatar Jun 29 '16 11:06 Niaro

if you want to use it in your app you currently need to build angular on your own

or u can use https://github.com/angular/router-builds

DzmitryShylovich avatar Jun 29 '16 22:06 DzmitryShylovich

+1

delagen avatar Jul 07 '16 14:07 delagen

As Brandon pointed out the way to achieve this is to do something like this:

router.events.filter(e => e instanceof NavigationEnd).forEach(() => {
  // inspect the state and set the title
  // router.routerState 
})

Closing the issue.

vsavkin avatar Jul 28 '16 22:07 vsavkin

In my opinion, the above plunkr is an overkill for such a simple thing we are trying to achieve here. Correctly labelled as non-obvious though , I hope there will be a shortcut solution in the future Could we reopen this for providing a shortcut as a feature ? should I open another issue or is this considered as final decision(no shorthands for this operation)?

agalazis avatar Jul 29 '16 17:07 agalazis

What about when page reloaded? Is NavigationEnd triggered when page reloaded?

tsu1980 avatar Aug 06 '16 11:08 tsu1980

@tsu1980 Yes all three, NavigationStart, RoutesRecognized and NavigationEnd are triggered when the page loads.

AndersAppelt avatar Aug 18 '16 11:08 AndersAppelt

still if you reload the page some information will be missing I will investigate further though and I will let you know. I guess it's because no all the routes are there as if you navigated to the age

agalazis avatar Aug 21 '16 07:08 agalazis

As a side note the two approaches suggested earlier doesn't work if there are multiple active router outlets. I found that in those cases you only get the data for the primary outlet. And the Navigation event is only triggered once. I ended up with the code below which gives me an array of Data objects. Injected in the constructor are router: Router and activated: ActivatedRoute.

this.sub = router.events
      .filter(event => event instanceof NavigationEnd)
      .subscribe(() => {
          let data: Data[] = [];
          let activeRoutes: ActivatedRoute[] = activated.children;

          activeRoutes.forEach((route: ActivatedRoute) => {
              let activeRoute: ActivatedRoute = route;
              while (activeRoute.firstChild) {
                  activeRoute = activeRoute.firstChild;
              }
              data.push(activeRoute.snapshot.data);
          });
      });
      // do something with data

AndersAppelt avatar Aug 22 '16 06:08 AndersAppelt

Any update ? 'firstChild' does not exist on type 'RouterState' anymore this is important if you had the shorthands you would keep that graph internally nothing would brake(eg. it would have the same interface).

agalazis avatar Sep 29 '16 09:09 agalazis

@agalazis firstChild exists on each ActivatedRoute now. The RouterState no longer handles traversing the route tree directly

brandonroberts avatar Sep 29 '16 19:09 brandonroberts

So how do we fix something like this now:

this.sub = this.router.events
    .filter(event => (event instanceof NavigationEnd))
    .map(_ => this.router.routerState)
    .map(state => {
      let route = this.activatedRoute;
      while (state.firstChild(route)) {
        route = state.firstChild(route);
      }
      return route;
    })
    .filter(route => route.outlet === PRIMARY_OUTLET)
    .flatMap(route => route.data)
    .subscribe( (data: any) => {
      this._updateMetaTags(data.meta);
    });

sunshineo avatar Oct 05 '16 06:10 sunshineo

If someone is looking for working solution, here it is, based on previous examples (but never blindly trust code snippets from the internet)

https://gist.github.com/alexbyk/0801373112b64bd171721c4b6b23e9e2

@sunshineo this might help you

alexbyk avatar Oct 07 '16 01:10 alexbyk

@alexbyk Forwarding to a project where this kind of code is used.

sunshineo avatar Oct 07 '16 06:10 sunshineo

Can this be reopened? The provided official solution does not work for multiple outlets and is anything but nice to use.

gitnik avatar Nov 16 '16 15:11 gitnik

This is a great answer: https://toddmotto.com/dynamic-page-titles-angular-2-router-events

avinashjoshi avatar Jan 18 '17 23:01 avinashjoshi