【问题标题】:Call api before page refresh angular在页面刷新角度之前调用api
【发布时间】:2019-11-21 11:03:46
【问题描述】:

我想在用户使用 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 被浏览器取消。谁能帮我吗 。谢谢。

【问题讨论】:

  • sessionTime 在哪里?你能解释一下吗 - Api 被浏览器取消了。
  • 你试过把 :unload 改成 :beforeunload 吗?你也可以试试 canDeactivate 钩子 - 不错的文章阅读medium.com/better-programming/…
  • 角度检查resolvers
  • 是的,我也尝试过使用 beforeunload 但浏览器取消了 api 调用。
  • @PrashantPimpale 这只是我们可以假设的任何数字。

标签: angular


【解决方案1】:

您可以在 Angular 中调用特定生命周期钩子上的函数。因此,就像当用户使用硬链接 <a href="...">...</a> 或刷新离开应用程序时,您可以使用 onDestory() 挂钩

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

您可以在此处获取有关官方文档中生命周期钩子的更多信息:https://angular.io/guide/lifecycle-hooks

【讨论】:

【解决方案2】:

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

阅读更多:https://angular.io/api/router/Resolve

【讨论】:

  • 我不希望在组件加载之前我希望它在硬重新加载或单击 href 标记时。
  • 只有你的 index.html 会在硬重新加载时运行。因此,您可以根据需要在其中添加一个脚本。
  • 但是我想要一些 api 来调用,我可以在其中跟踪他/她在一页中访问过的访问者的时间。让我们说跟踪会话。
猜你喜欢
  • 1970-01-01
  • 2017-08-28
  • 2021-01-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-29
  • 2018-01-18
  • 1970-01-01
相关资源
最近更新 更多