Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 4 Router - Hook each router changes

I would like to create a Breadcrumb.

Breadcrumb Wikipedia

And for this, I thought about creating a Service to handle it. But I need to hook each router changes, a method or a class that will be used everytime the router state change.

This challenge have to be resolved without adding a onActivate method in all my components because I have a lot of them.

Great thanks !

like image 216
SakiiR Avatar asked Aug 28 '17 10:08

SakiiR


People also ask

How does Angular determine routing change?

In order to detect route change at any moment in AngularJS, this can be achieved by using the $on() method.

Can we use 2 router outlet in Angular?

You can have multiple router-outlet in same template by configuring your router and providing name to your router-outlet, you can achieve this as follows. Advantage of below approach is thats you can avoid dirty looking URL with it. eg: /home(aux:login) etc.

Can we have multiple routes in Angular?

Auxiliary routes allow you to use and navigate multiple routes. To define an auxiliary route you need a named router outlet where the component of the auxiliary route will be rendered. Since we are using an empty path, the sidebar component will be rendered when our application is started.

Can we define multiple router outlets in a component view?

Yes! We can use multiple router-outlets in same template by configuring our routers and simply add the router-outlet name. You can see in the example.


1 Answers

You can use Router events to track route changes

import { Router, NavigationEnd } from '@angular/router';
import 'rxjs/add/operator/filter';

class MyService {

  constructor(private router: Router) {
    this.router.events
      .filter(e => e instanceof NavigationEnd)
      .subscribe(e => console.log('Route changed: ' + e.url);

  }

}
like image 132
taras-d Avatar answered Oct 07 '22 12:10

taras-d