首页 > 解决方案 > 如何通过使用 HostListener 在 Angular 8 中关闭浏览器来调用事件或 API,

问题描述

我需要在我的项目中关闭浏览器时调用一个简单的 websocket clousure API,我尝试使用 HostListener,但它不起作用。下面是代码https://stackblitz.com/edit/angular-nm7uww

app.component.html

<hello name="{{ name }}"></hello>
<p>
  Start editing to see some magic happen :)
</p>

app.component.ts

import { HostListener,Component,OnInit  } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular';
ngOnInit() {
      @c('window:beforeunlosd', ['$event'])
    beforeunloadHandler(event){

    }
  }
}

标签: angulartypescript

解决方案


语法不正确,使用:

  @HostListener("window:beforeunload", ["$event"])
  beforeunloadHandler(event) {
    console.log("closing");
    // rest of your code
  }

您不能在另一个方法中声明一个方法。


推荐阅读