2 回答

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事件中的取消订阅。

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