0

Host listener doesn't work. The function which triggers the request is being called but, the post-operation does not invoked. Can anyone help with this?

app.component.ts

@HostListener('window:beforeunload', ['$event'])
onWindowClose($event) {
    console.log('market unlocked');
    this.unlockAlias();
    return true;
}

constructor(private router: Router, private service: Adal5Service, private http : Http) {
    this.service.init(config);
}

ngOnInit() {
    this.service.handleWindowCallback();
    this.isAuthenticated = this.service.userInfo.authenticated;
}

unlockAlias() {
     const apiEndPoint = environment.baseUrl + environment.unLockAlais;
    const body = '{"uid": "' + this.service.userInfo.username + '" }';
    const headers = new Headers({ 'Content-Type': 'application/json' });
    headers.append('Access-Control-Allow-Origin', '*');
    const options = new RequestOptions({ headers: headers });
    this.http
        .post(apiEndPoint,
        body, options)
        .subscribe(data => {
            console.log("unlocked");
        }, error => {
            console.log(JSON.stringify(error.json()));
        });
}}
Roysh
  • 1,542
  • 3
  • 16
  • 26
Harshit Chawla
  • 113
  • 1
  • 9

2 Answers2

0

I don't think you'll be able to POST asynchronously in the beforeunload, as the function will terminate and the user will navigate away from the page before your subscription resolves.

You could make a synchronous (blocking) call yourself, but Angular does not support that (because it's a bad idea), so you would have to do it the old fashioned way.

chrispy
  • 3,552
  • 1
  • 11
  • 19
0

It worked after i altered the unlockAlias() to return the http result , which is an Observable and subscribed it on ('window:beforeunload') event.

@HostListener('window:beforeunload', ['$event'])
onWindowClose($event) {
    this.unlockAlias().subscribe();

 unlockAlias() {
    const apiEndPoint = environment.baseUrl + environment.unLockAlais;
    const body = '{"uid": "' + this.service.userInfo.username + '" }';
    const headers = new Headers({ 'Content-Type': 'application/json' });
    headers.append('Access-Control-Allow-Origin', '*');
    const options = new RequestOptions({ headers: headers });
    return this.http.post(apiEndPoint, body, options);
}
Harshit Chawla
  • 113
  • 1
  • 9