0

I am working in an Angular4 project ,In this I need to pass the date and time to API when the user close the browser window closed. Is it possible ? If it's possible means how it could be implemented..?

Now I'm passing the date and time to API on page load ....

import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { DatePipe } from '@angular/common';

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
})

export class AppComponent implements OnInit{
    today = Date.now();
    fixedTimezone =this.today;
    res : string;

    constructor(private http: HttpClient) {}

    ngOnInit() {
        this.http.get('http://freegeoip.net/json/?callback')
                 .subscribe(
                    data => this.saveIP(data['ip']),
                    error => console.error(error)
                 );
    }

     saveIP(address: string) {
        this.http.get(`http://localhost:57036/api/data/GetClientIp/?IP_Address=${address}&Time=${this.fixedTimezone}`)
                 .subscribe(data => this.res = data['']);
    }

}

like the way I want to pass the date and time on page close....

Thanks...

Code Hunter
  • 153
  • 1
  • 3
  • 12

1 Answers1

0

You can use @HostListener to listen to beforeunload event. Unfortunately there's no gurantee that your request will be called.

@HostListener('window:beforeunload', ['$event'])
beforeunloadHandler(event) {
  // make request to API
}
Mateusz Witkowski
  • 1,646
  • 10
  • 24