2 回答

TA貢獻2080條經(jīng)驗 獲得超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條經(jīng)驗 獲得超9個贊
我在這里分析的問題是,每當構(gòu)造函數(shù)運行時,都會發(fā)生問題。它將肯定會調(diào)用您的函數(shù)。因此,您必須檢查此功能是否以前已經(jīng)運行過。 最簡單的答案是
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');
}
});
}
基本上,您必須根據(jù)自己的意愿來管理PopCalled的狀態(tài),據(jù)我所知,這是最簡單的方法。
添加回答
舉報