为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

慕村225694 2021-04-08 17:15:25
我有以下代码使用角度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。
查看完整描述

2 回答

?
犯罪嫌疑人X

TA贡献2080条经验 获得超4个赞

您只需要在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事件中的取消订阅。


查看完整回答
反对 回复 2021-04-22
?
眼眸繁星

TA贡献1873条经验 获得超9个赞

我在这里分析的问题是,每当构造函数运行时,都会发生问题。它将肯定会调用您的函数。因此,您必须检查此功能是否以前已经运行过。 最简单的答案是


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的状态,据我所知,这是最简单的方法。


查看完整回答
反对 回复 2021-04-22
  • 2 回答
  • 0 关注
  • 161 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信