Skip to content

Data object is missing in router 3.0.0-alpha #9390

Closed

Description

@fursad

Hi,
This is not a typical issue, but I am upgrading my exisiting solution to the new 3.0.0-alpha router. I discovered that the data object from the old router is gone. What is the alternative for us that used the data object property to have some additional info about the route?

Regards
Shakil

Activity

  1. choeller commented on Jun 21, 2016

    @choeller
    Contributor

    I created an issue in the router-repo some days ago https://github.com/angular/vladivostok/issues/43 I think currently there is no alternative.

  2. vicb commented on Jun 21, 2016

    @vicb
    Contributor

    @vsavkin could you please take a look ? Do we plan to have an upgrade doc ?

  3. choeller commented on Jun 21, 2016

    @choeller
    Contributor

    I think there is currently also no way to access the configuration of the currently active route, or am I missing something?

  4. brianchance commented on Jun 23, 2016

    @brianchance

    +1

    @choeller - looks like you can access the current route config using (would prefer next.route or next.routeConfig)

    canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
        let path = next._routeConfig.path;
    }
  5. un33k commented on Jun 25, 2016

    @un33k

    If you still need data on your route config, it will cost you lots of headache ... Angular 2 is not as DRY as it should be at this moment. Looking forward to router-RC.

    Hope this helps!

    app.routes.ts

    import { Route } from '@angular/router';
    
    // create our own custom RouteConfig
    interface AppRouterConfig extends Route {
      data?: any;
    }
    
    // Add data which is optional - Here we add title of each route as an example
    export const topRoutes: Array<AppRouterConfig> = [
      { path: 'home',  component: HomeComponent },
      { path: 'about', component: AboutComponent, data: {title: 'About'} },
      { path: '**',    component: UnfoundComponent, data: {title: 'Not Found (404)'} },
    ];

    app.component.ts

    import { Title } from '@angular/platform-browser';
    import { Router, NavigationEnd } from '@angular/router';
    
    import { topRoutes as knownRoutes} from './app.routes';
    
    @Component({
      selector: 'app',
      // ... stuff
    })
    export class App implements OnInit {
      constructor(
        private router: Router,
        private title: Title) {
      }
     name: string = 'My Site';
    
      ngOnInit() {
      // change page title and scroll to top of the page on route change
        this.router.events.subscribe(s => {
            if (s instanceof NavigationEnd) {
            this.title.setTitle(this.getRouteTitle(s.url));
            window.scrollTo(0, 0);
          }
        }); 
      }
    
      getRouteTitle(url: string): string {
      // go through the route config(s) and fish out the title if any - Todo: cache title for next time
      // Alternatively - we may be able to get each route config directly, perhaps from CanActivate
      var title: string = this.name;
        for (var item of knownRoutes) {
          if (url == `/${item.path}` && 'data' in item && 'title' in item.data) {
            title = `${title} | ${item.data.title}`;
            break;
          }
        }
        return title;
      }
    }
  6. brianchance commented on Jun 25, 2016

    @brianchance

    @un33k - Your solution does work, but cannot be used it with child routes since Route declares children?: Route[] and Typescript does not allow it to be redeclared.

  7. un33k commented on Jun 25, 2016

    @un33k

    @brianchance - This should work with children too. Route needs to be extended as well.

    Also - I won't call it a solution as it is just playing around at this time. I am sure NG2 team will take their sweet time and include all these goodies into the final Router.

  8. un33k commented on Jul 3, 2016

    @un33k

    Great .. now how do you access the data on a route NavigationEnd event? The idea (as per code above) is to set the page title based on the title key in the route data.

      { path: 'about', component: AboutComponent, data: {title: 'About'} },
  9. zoechi commented on Jul 3, 2016

    @zoechi
    Contributor

    @un33k

    you can subscribe to data like

    class HeroDetailComponent {
      ngOnInit() {
        this.sub = this.route
          .data
          .subscribe(v => console.log(v));
      }
    
      ngOnDestroy() {
        this.sub.unsubscribe();
      }
    }
    
  10. un33k commented on Jul 3, 2016

    @un33k

    @zoechi (thx) : For a simple task of changing the page title, each routable component must have the above code.

    If route change event provided an easy access to the route itself, then a shared service could have been put in place to simply swap the title and do other route specific tasks.

    Something like this on the app.component:

    export class App {
    
      ....
      constructor(private router: Router, private: title: Title) {}
    
      ngOnInit() {
        this.router.events.subscribe(s => {
            if (s instanceof NavigationEnd) {
               let d = s.route.data; // if this was possible
               this.title.setTitle(d.title);
               window.scrollTo(d.x, d.y);
          }
        }); 
      }
      ....
    }

    The route data is immutable right? If so, do we need to subscribe to get it? A reference to it, or a copy of it would do!

  11. choeller commented on Jul 3, 2016

    @choeller
    Contributor

    @un33k I already opened issue #9662 for that. Meanwhile you can use the following as a workaround:

      constructor(
        public router: Router,
        public activated: ActivatedRoute,
        public titleService: Title
      ) {}
    
      ngOnInit() {
        this.sub = this.router.events
          .filter(event => event instanceof NavigationEnd)
          .map(_ => this.router.routerState)
          .map(state => {
            let route = this.activated;
            while(state.firstChild(route)) {
              route = state.firstChild(route);
            }
            return route;
          })
          .map(route => route.snapshot.data)
          .subscribe(data => {
            this.titleService.setTitle(data['title'] || "My default title");
          });
      }
  12. un33k commented on Jul 3, 2016

    @un33k

    @choeller works (thx). Hopefully, simple tasks like this would be provided out of the box.

  13. angular-automatic-lock-bot commented on Sep 9, 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.

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

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions