How do I detect user navigating back in Angular2?

前端 未结 6 1758
离开以前
离开以前 2020-11-27 15:01

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.

constr         


        
相关标签:
6条回答
  • 2020-11-27 15:41

    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();
    }
    
    0 讨论(0)
  • 2020-11-27 15:43

    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!');
    
        });
    
    }
    
    (...)
    
    0 讨论(0)
  • 2020-11-27 15:47
    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.

    0 讨论(0)
  • 2020-11-27 15:48

    in angular 8+

    constructor(private readonly route: Router) {
    this.route.events
      .pipe(filter((event) => event instanceof NavigationStart))
      .subscribe((event: NavigationStart) => {
        if (event.restoredState) {
          this.isBackUrl = true;
        }
      });
    

    }

    0 讨论(0)
  • 2020-11-27 15:56

    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.

    0 讨论(0)
  • 2020-11-27 16:04

    This solution works for all versions of Angular.

    import { PlatformLocation } from'@angular/common';
    
    constructor( private _location: PlatformLocation ) {
    
    this._location.onPopState (() => {
     `enter code here` // You could write code to display a custom pop-up here.
    
     // window.location.href = 'https://www.google.com'; //Navigate to another location when the browser back is clicked.
    
    
    });
    
    0 讨论(0)
提交回复
热议问题