Angular2: Detect change in route in Angular2

Standard

In order to get information about landing page Url and previous page Url in Angular2, use below mentioned solutions:

Solution 1:

import { Router, NavigationStart, Event as NavigationEvent } from '@angular/router';

constructor(router:Router) {
  router.events.forEach((event: NavigationEvent) => {
    if(event instanceof NavigationStart) {
    }
    // NavigationEnd
    // NavigationCancel
    // NavigationError
    // RoutesRecognized
  });
}

Solution 2:

You can also filter by the given event:

import 'rxjs/add/operator/filter';

constructor(router:Router) {
  router.events
    .filter(event => event instanceof NavigationStart)
    .subscribe((event:Event) => {
      // You only receive NavigationStart events
    });
}

Solution 3:

import 'rxjs/add/operator/pairwise';
import {Router} from '@angular/router;

export class AppComponent {
    constructor(private router: Router) {
        this.router.events.pairwise().subscribe((e) => {
            console.log(e);
        }
    });
}
Advertisements

One thought on “Angular2: Detect change in route in Angular2

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s