猿问

Angular 6-后退按钮按下触发不止一次

我有以下代码使用角度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.location.unsubscribe(),但是找不到类似的函数location。


慕村225694
浏览 162回答 2
2回答

犯罪嫌疑人X

您只需要在ngOnDestroy生命周期挂钩破坏组件时退订。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');      }    });  }}正如briosheje在评论中提到的那样,生命周期挂钩不会在浏览器刷新时运行。为此,您需要处理文档onbeforereload事件中的取消订阅。

眼眸繁星

我在这里分析的问题是,每当构造函数运行时,都会发生问题。它将肯定会调用您的函数。因此,您必须检查此功能是否以前已经运行过。 最简单的答案是constructor( private location: Location){ const PopCalled = localStorage.getItem('PopCalled') if(!PopCalled)  this.handleBackButtonPress();}handleBackButtonPress() { this.subscribed = true;  this.location.subscribe(redirect => {  if (redirect.pop === true) {  localStorage.setItem('PopCalled', true);  alert('this is a backbutton click');  } });}基本上,您必须根据自己的意愿来管理PopCalled的状态,据我所知,这是最简单的方法。
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答