Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 6 - Back button press trigger more than once

I have the following code to detect the back button press using angular 6.

import { Location } from '@angular/common';
export class ProductsComponent implements OnInit {

constructor( private location: Location){
  this.handleBackButtonPress();
}
  handleBackButtonPress() {
    this.subscribed = true;
    this.location.subscribe(redirect => {
     if (redirect.pop === true) {
      alert('this is a backbutton click');
     }
    });
  }
}

This is working and we got alert on back button press. The problem is If we visit the same page more than once it will trigger the alert with the number of time we visited the route with the same component.

Note: I have checked for a solution like this.location.unsubscribe(), But failed to find a function like that for location.

like image 505
Shijin TR Avatar asked Apr 08 '19 13:04

Shijin TR


1 Answers

You just need to unsubscribe when the component is destroyed by the ngOnDestroy lifecycle hook.

import { Location } from '@angular/common';
import { SubscriptionLike } from 'rxjs';

export class ProductsComponent implements OnInit, OnDestroy {

  public subscription: SubscriptionLike;

  constructor(private location: Location){
    this.handleBackButtonPress();
  }

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

  handleBackButtonPress() {
    this.subscription = this.location.subscribe(redirect => {
      if (redirect.pop === true) {
        alert('this is a backbutton click');
      }
    });
  }
}

As mentioned by briosheje in the comments the lifecycle hook does not run on browser refreshes. For that you'll need to handle the unsubscription on the document's onbeforereload event.

like image 67
Daniel Avatar answered Oct 24 '22 06:10

Daniel