0

I'm experiencing a strange situation under Google Chrome (newest) - I'm navigating to a list in my ng2 driven web application, collapsing the browser to the task bar and after 5 minutes (or so), the console is showing messages that are being shown when my component gets initiated the first time, so:

public ngOnInit(): void {
    console.log("INIT CALLED");
}

So it looks like Chrome is killing my application, then it gets resurrected and is showing this INIT CALLED message. What kills me is that ngOnDestroy hook is not called before ngOnInit gets called the second time. Looks like a bug in ng2 for me, but has anybody experienced this and can share a fix with me?

Marek M.
  • 3,799
  • 9
  • 43
  • 93

1 Answers1

0

ngOnDestroy isn't called when the browser tab is closed or suspended.
ngOnDestroy is only called when Angular removes a component.

When the tab is closed, Angular doesn't get a chance to do anything. See How can we detect when user closes browser? about how to invoke code when the browser tab is closed.

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • Have you even read my question? `ngOnDestroy` part of it was like one sentence, the real problem is that ngOnInit is called multiple times... – Marek M. Oct 30 '17 at 13:01
  • When the app is destroyed and re-initialized, it's expected `ngOnInit` is called again. – Günter Zöchbauer Oct 30 '17 at 13:02
  • You can check in chrome://discards if your tab was discarded. – Günter Zöchbauer Oct 30 '17 at 13:04
  • Ok, so if I get it correctly, should I just put a flag somewhere to check if ngOnInit was already invoked, if I want some code inside it to be invoked only once? – Marek M. Oct 30 '17 at 13:04
  • If you want it to be invoked only once the application starts, then you should probably leave it as it is. It depends what you mean exactly by "only once". – Günter Zöchbauer Oct 30 '17 at 13:05
  • I'm observing (RxJS) stream of scroll events - if I do it twice, then behavior is getting very weird (scroll events triggered, when there's no scrolling), so by saying I want it to be invoked only once - I mean just that - event handlers should be hooked up only once. – Marek M. Oct 30 '17 at 13:09
  • Can't imagine. If the tab is discarded, the application application is loaded when the tab is restored like you would do a full page reload. If you would set a flat, that would be lost after the tab is restored. – Günter Zöchbauer Oct 30 '17 at 13:10
  • Yep, the problem is that I don't know if the tab is discarded, or suspended. The behaviour however is that event handlers are being connected twice thus resulting in the described behaviour. Maybe there's something wrong with RxJS then... – Marek M. Oct 30 '17 at 13:12
  • I wasn't able to find any details about the behavior of discarded tabs. I can't imagine event handlers being connected twice. When the tab is discarded and reloaded, the previous connection is lost. – Günter Zöchbauer Oct 30 '17 at 13:17