1

With previous angular2 routers, I were able to get component name by url.

            console.log(this.router.instruction);
            console.log(this.router.currentInstruction.component);
            console.log(this.router.currentInstruction.component.routeName);

But with new Router I can't. Is there any alternatives?

I want to track every routing in my app, then will log it with it's component name(not url value)

constructor(private router: Router,
            private cookieService: CookieService,
            private adminService: AdminService,
            private appService: AppService) {
    router.events.subscribe((e: Event) => {
        if (e instanceof NavigationEnd) {

            //
            // WANT TO GET COMPONENT NAME by this.router.url
            //

            let newRoute = this.router.url || '/';
            if (this.currentRoute != newRoute) {
                console.log('route to ', newRoute);
                this.currentRoute = newRoute;
            }
        }
    });
}

any chance?

Jihun No
  • 1,201
  • 1
  • 14
  • 29

1 Answers1

0

You can access active route as below code snippet

constructor(private router:Router, private currentActivatedRoute:ActivatedRoute)
ngOnInit()
{
var comp = this.currentActivatedRoute.component
}

If you need to access child activated route in parent componet see

ActivatedRoute

Community
  • 1
  • 1
Arpit Agarwal
  • 3,993
  • 24
  • 30
  • Hey @Arpit Agarwal . It always return same component. I subscribed the event observer in a single component to track All of the routing over site. – Jihun No Aug 03 '16 at 12:22
  • See the linked post. You can get ActivatedRoute of children and use that tree to find the leaf node . The component you subscribe to has to be root for that to work. – Arpit Agarwal Aug 03 '16 at 12:25
  • Alternatively you can write a canActivateGuard which have the same/similar param as described in my post and log from there. You have to pass that hook in route config of all element. Btw isn't logging on ngOnInit of individual components suffice your usecase. – Arpit Agarwal Aug 03 '16 at 12:29