How do I detect user navigating back in Angular2?

夙愿已清 提交于 2019-12-17 05:49:10

问题


I have a component and I need to detect if user pressed back button in his browser to navigate back.

Currently I'm subscribing router events.

constructor(private router: Router, private activatedRoute: ActivatedRoute) {

    this.routerSubscription = router.events
        .subscribe(event => {

            // if (event.navigatesBack()) ...

        });

}

I know that I can use window.onpopstate but it feels like a hack when using Angular2.


回答1:


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

import { PlatformLocation } from '@angular/common'

(...)

constructor(location: PlatformLocation) {

    location.onPopState(() => {

        console.log('pressed back!');

    });

}

(...)



回答2:


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.




回答3:


import { HostListener } from '@angular/core';

and then listen for popstate on the window object:

  @HostListener('window:popstate', ['$event'])
  onPopState(event) {
    console.log('Back button pressed');
  }

This code works for me on latest Angular 2.




回答4:


As thorin87 answer dont use PlatformLocation. We need subscribe an unsubscribe.

import {Subscription} from 'rxjs/Subscription';    

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

ngOnDestroy() {
  this.subscription.unsubscribe();
}


来源:https://stackoverflow.com/questions/40381814/how-do-i-detect-user-navigating-back-in-angular2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!