Skip to content

feat(router) add possibilty to subscribe to current ActivatedRoute #9662

Closed

Description

@choeller

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 ]

Activity

  1. added
    feature
    on Jun 28, 2016
  2. brandonroberts commented on Jun 28, 2016

    @brandonroberts
    Contributor

    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

  3. choeller commented on Jun 28, 2016

    @choeller
    ContributorAuthor

    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

  4. Niaro commented on Jun 29, 2016

    @Niaro

    @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...

  5. choeller commented on Jun 29, 2016

    @choeller
    ContributorAuthor

    @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.

  6. Niaro commented on Jun 29, 2016

    @Niaro

    @choeller Okay...( Thank you)

  7. DzmitryShylovich commented on Jun 29, 2016

    @DzmitryShylovich
    Contributor

    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

  8. delagen commented on Jul 7, 2016

    @delagen
    Contributor

    +1

  9. vsavkin commented on Jul 28, 2016

    @vsavkin
    Contributor

    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.

  10. agalazis commented on Jul 29, 2016

    @agalazis

    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)?

  11. tsu1980 commented on Aug 6, 2016

    @tsu1980

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

  12. AndersAppelt commented on Aug 18, 2016

    @AndersAppelt

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

  13. agalazis commented on Aug 21, 2016

    @agalazis

    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

  14. AndersAppelt commented on Aug 22, 2016

    @AndersAppelt

    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
    
  15. agalazis commented on Sep 29, 2016

    @agalazis

    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).

  16. brandonroberts commented on Sep 29, 2016

    @brandonroberts
    Contributor

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

  17. sunshineo commented on Oct 5, 2016

    @sunshineo

    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);
        });
    
  18. alexbyk commented on Oct 7, 2016

    @alexbyk
    Contributor

    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

  19. sunshineo commented on Oct 7, 2016

    @sunshineo

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

  20. gitnik commented on Nov 16, 2016

    @gitnik

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

  21. avinashjoshi commented on Jan 18, 2017

    @avinashjoshi
  22. delagen commented on Jul 7, 2017

    @delagen
    Contributor

    @KSuttle-cng update title on route change from route data

  23. angular-automatic-lock-bot commented on Sep 12, 2019

    @angular-automatic-lock-bot

    This issue has been automatically locked due to inactivity.
    Please file a new issue if you are encountering a similar or related problem.

    Read more about our automatic conversation locking policy.

    This action has been performed automatically by a bot.

  24. locked and limited conversation to collaborators on Sep 12, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    area: routerfeatureworkaround2: non-obvious

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions