0

I want to call api before user navigates to url using href or reloading the current page. Here's my code that i have used.

@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 is cancelled by the browser. Can anyone help me out . Thanks.

enter image description here

user6795317
  • 141
  • 4
  • 10

2 Answers2

1

You can call functions on specific lifecycle hooks in Angular. So like when the user leaves the application with a hard link <a href="...">...</a> or refresh you can take the onDestory() hook

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

Here you can get additional information about life cycle hooks in the offical documentation: https://angular.io/guide/lifecycle-hooks

Ling Vu
  • 4,740
  • 5
  • 24
  • 45
0

You can use a resolver in router to resolve data before the component loads.

Read more at: https://angular.io/api/router/Resolve

Muhammad Kamran
  • 978
  • 6
  • 10