Shi*_*jin 7 javascript typescript 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');
}
});
}
}
Run Code Online (Sandbox Code Playgroud)
这正在工作,我们在按下后退按钮时收到了警报。问题是,如果我们多次访问同一页面,它将以我们访问具有相同组成部分的路线的时间触发警报。
注意:我已经检查了类似的解决方案this.location.unsubscribe(),但是找不到类似的功能location。
您只需要在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');
}
});
}
}
Run Code Online (Sandbox Code Playgroud)
正如briosheje在评论中提到的,生命周期钩子不会在浏览器刷新时运行。为此,您需要处理文档onbeforereload事件的取消订阅。
| 归档时间: |
|
| 查看次数: |
665 次 |
| 最近记录: |