Angular 在页面刷新之前调用api

Angular 在页面刷新之前调用api,angular,Angular,我想在用户使用href导航到url或重新加载当前页面之前调用api。这是我使用过的代码 @HostListener('window:unload', ['$event']) unloadHandler(event) { console.log('window:unload'); this.storeSessionVistorsCount(); } storeSessionVistorsCount() { if (this.sessionTime > 0) { c

我想在用户使用href导航到url或重新加载当前页面之前调用api。这是我使用过的代码

@HostListener('window:unload', ['$event'])
 unloadHandler(event) {
 console.log('window:unload');
 this.storeSessionVistorsCount();
}

storeSessionVistorsCount() {
    if (this.sessionTime > 0) {
      const body = {
        ip: this.ipAddress,
        space_id: this.spaceId,
        type: 'session',
        time: this.sessionTime
      };
      this.statisticService.getIpDetail(body).subscribe((res: any) => {
        console.log('success')
      }, err => {
        console.log(err);
      });
    }
  }

Api被浏览器取消。有人能帮我吗。谢谢


您可以在Angular中调用特定生命周期挂钩上的函数。因此,就像当用户使用硬链接离开应用程序时一样,您可以使用
onDestory()
钩子

@Component({selector: 'my-cmp', template: `...`})
class MyComponent implements OnDestroy {
  ngOnDestroy() {
    // Make your api call
  }
}

在这里,您可以在官方文档中获得有关生命周期挂钩的更多信息:

您可以在加载组件之前使用路由器中的解析器解析数据


更多信息请访问:

哪里是
sessionTime
?你能解释更多吗?Api被浏览器取消了。你有没有试过将:卸载改为:beforeunload?您也可以尝试canDeactivate hook-很好的文章阅读check in angularYes我也尝试过使用PreforeUnload,但浏览器取消api调用。@PrashantPimple这只是我们可以假设的任何数字。它不会在硬重新加载或href标记中检测到Ngondestry。也许这有帮助:我不想在加载组件之前硬重新加载或单击它在href tag.well上,只有您的index.html会在硬重新加载时运行。所以,如果你愿意的话,你可以在那里添加一个脚本。但是我想要一些api来调用,我可以在一个页面中跟踪访问者访问过的地方的时间。比如说跟踪会话。