0

In angularjs 1.x with Ui Router module I could subscribe to state/route changes in ONE class like app.js when the route from ANY state/controller changed.

How can impl. the same behavior with ng2?

I want just ONE subscribe for the route.params in ONE class where I can check the url and then decide what to do.

I thought the app.component.ts is the right place for it, but the route change there happens only when the whole page is refereshed!

Or is it possible that a component can have a base class where I can implement base functionality just one time ? This just came to my mind...

Pascal
  • 12,265
  • 25
  • 103
  • 195

2 Answers2

0

It's not that simple. Not every route has to have a specific parameter. You can create a routed compononent that is added by a route where that parameter is defined and make all other routes child routes of this route. Then add the subscriptions to the parameter to this top routed component.

Another approach would be to subscribe to router events like explained in Angular 2 router event listener and then read the params from the router state of the first child route.

Community
  • 1
  • 1
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • Approach1 will not work for me as I have no child routes technically seen. I have a project list view where you open a project and then dive into the rest of the data with more side by side views. But the projects route is not having the children property! But I see this would have multiple advances and I am really thinking about redesigning my projects page to be a parent. Approach 2 would be terrible having to subscribe to NavEnd and Nav start in each component. I have just read that ng2.3 support full component inheritence: https://scotch.io/tutorials/component-inheritance-in-angular-2 – Pascal Jan 02 '17 at 14:51
  • ...that could make the whole subscribing easier maybe. The more I think about the parent/child approach the more I do not understand why in the past I have so much fighted against it. Seems its all about understanding things as time passes by ;-) – Pascal Jan 02 '17 at 14:52
0

Try this: 1) create a service route-log.service.ts and inject Router to it and do the logging work. 2) provide route-log.service.ts in your app.module.ts.

Timathon
  • 1,049
  • 9
  • 11
  • Can you explain more? I dont see how that matches my question :-) – Pascal Jan 03 '17 at 09:43
  • It's a service which is injected at the app.module.ts (root), so it will run once the app starts up. And you can inject Router in that service to "subscribe to state/route changes". – Timathon Jan 03 '17 at 10:04