首页 > 解决方案 > 如何在浏览器/标签关闭时发送 API 请求?

问题描述

我正在尝试在关闭选项卡/浏览器时发送 API 请求,我尝试过卸载和beforeUnload处理程序,但它不起作用,我猜测 API 调用没有发生,因为选项卡/浏览器立即关闭,并且没有足够的时间进行请求,在使用调试器关键字进行测试期间一切正常,但并非没有。知道如何在关闭标签/浏览器之前拨打电话吗?

我的代码如下

组件.ts

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
  title = 'admin-frontend';

  constructor(private loginService: LoginService) {}

  ngOnInit() {}

  @HostListener('window:unload', ['$event'])
  unloadHandler(event) {
    if (!!this.loginService.currentUser) {
      this.loginService.logout({});
    }
  }

  // вызов логаут когда клиент закрывает браузер или окно
  @HostListener('window:beforeunload', ['$event'])
  beforeUnloadHandler(event) {
    if (!!this.loginService.currentUser) {
      this.loginService.logout({});
    }
  }
}

服务.ts

    logout(params) {
        return this.post('user/logout', { ...params }, true).subscribe(_ => {
            this.applicationId = null;
            this.userData.next(null);
            this.loginFacade.userData.next(null);
            this.storage.clear();
            this.user = undefined;
            this.router.navigate(['login']);
        })
    }

核心服务.ts

  post<T>(url: string, param: any, withHeader: boolean = false): Observable<T> {
    if (withHeader) {
      const headers: HttpHeaders = new HttpHeaders({
        SessionId: this.user.sessionId,
      });
      return this.http.post<T>(`${this.apiUrl}/${url}`, param, {
        headers: headers,
      });
    } else {
      return this.http.post<T>(`${this.apiUrl}/${url}`, param);
    }
  }

标签: javascriptangularbrowserdom-events

解决方案


您好,您可以使用此功能检测浏览器关闭

window.onbeforeunload = function () {
    return "Do you really want to close?";
};

推荐阅读