我想在用户使用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被浏览器取消。谁能帮我吗 。谢谢。
答案 0 :(得分: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
答案 1 :(得分:0)
您可以在路由器中使用解析器在组件加载之前解析数据。