How do I detect user navigating back in Angular2?

IMO better method of listenting for popstate events is to subscribe to location service

import {Location} from "@angular/common";

constructor(private location: Location) { }

ngOnInit() {
    this.location.subscribe(x => console.log(x));
}

It doesn't use PlatformLocation directly (as documentation suggest) and you can unsubscribe any time you want.



EDIT Please don't do this.

The official docs say "This class should not be used directly by an application developer. Instead, use Location." Ref: https://angular.io/api/common/PlatformLocation


It's possible to use PlatformLocation which has onPopState listener.

import { PlatformLocation } from '@angular/common'

(...)

constructor(location: PlatformLocation) {

    location.onPopState(() => {

        console.log('pressed back!');

    });

}

(...)