ngOnDestroy在打开和关闭组件时起作用。离开网站时不行。角度

时间:2018-12-10 15:11:37

标签: angular

我的角度应用程序中有一个组件,希望在用户离开网站/应用程序后处理一些信息。

chat.component.ts

  ngOnDestroy() {
    this.chatService.newUserCount.subscribe(data => {
      this.chatCount = data--;
    });
    this.chatService.removeUser();
    this.chatService.sendMessage('User has left');
    this.chatService.leaveChat('User left');
  }

我有一个切换按钮,用于显示/隐藏上述组件。关闭组件时,ngOnDestroy()可以工作,并且代码可以正确执行。但是,当用户离开网站时,代码不会执行。我究竟做错了什么?我在错误的代码部分中这样做吗?

2 个答案:

答案 0 :(得分:1)

在这种情况下,您不能使用ngDestroy。您将必须使用浏览器默认值 unloadbeforeunload方法。可以将它与HostListner

一起使用

尝试这样的事情:

export class AppComponent  {

  name = 'Angular';
   @HostListener('window:beforeunload')
  doSomething() {
  }
    @HostListener('window:unload', [ '$event' ])
  unloadHandler(event) {
    // ...
  }
}

这是工作示例: https://stackblitz.com/edit/angular-cax8jw

希望这会有所帮助

答案 1 :(得分:0)

@siddharth shah的回答很好,但是限制了开发人员只能将AppComponent用于处理unload事件。例如,@HostListener在服务中不起作用。

这是允许您使用ngOnDestroy方法处理unload事件的解决方案。

@Injectable({
  providedIn: 'root'
})
export class MyService implements OnDestroy {


constructor(){
   this.startListening();
}

private startListening(): void {
   window.addEventListener("beforeunload", this.ngOnDestroy.bind(this));
}

private stopListening(): void {
   window.removeEventListener("beforeunload", this.ngOnDestroy.bind(this));
}

  ngOnDestroy(){

    //your own code here...

    this.stopListening();

  }

}
相关问题