如何在Angular5中的页面刷新时添加自定义确认框?

Kri*_*hna 1 typescript angular

我编写了一些代码,它将根据浏览器本地存储中存储的标志向我显示一个确认对话框。

if(localStorage.getItem('visitedPage') == 'true') {
  this.alertService.confirmThis("Are you sure?",function(){
    console.log("Yes");
  },function(){
    console.log("No");
  })
} else {
  localStorage.setItem('visitedPage','true');
}
Run Code Online (Sandbox Code Playgroud)

But I can see that dialog only after the page refresh (the entire content goes off, the page loads & the dialog opens). But I need that dialog immediately on hitting refresh.

Any suggestions or examples please!!

Pra*_*ana 7

在角度如果你想捕获刷新事件你可以这样做

//this should be parent component , in your case it should be app.component

@Component({ 
  selector: 'xxx',
  ..
)}
class MyComponent {
  @HostListener('window:beforeunload',['$event'])
  showMessage($event) {
     $event.returnValue='Your data will be lost!';
  }
}
Run Code Online (Sandbox Code Playgroud)