0

What's your best practice to avoid a component to trigger multiple times the same function when leaving and coming back to some page ?

I went into this issue when creating a user list that would trigger some getContent() each time the user scroll to the bottom of the page. The problem is each time you leave and come back to user list page, it will create a new instance of the service and trigger x times the getContent() function.

I'm using ngOnDestroy() and reset the getContent() method to avoid multiple calls but I'm sure either there's something wrong in my code or there is a best way to do it... Than :

ngOnDestroy() {
     this.items.clear();
     this.getContent = ():void => {};
};

Thanks a lot for your advices/opinions.

M

PS: plnkr is down, I will post one ASAP

martin
  • 93,354
  • 25
  • 191
  • 226
kfa
  • 2,106
  • 4
  • 17
  • 22
  • Even if this is not about http calls, just use a service which are instantiated only once if provided only once and do the call there if it hasn't happened yet. – Günter Zöchbauer Jun 20 '16 at 09:04
  • Thanks for the answer Günter. I read that post but that only applies to the Observable while I'm trying to avoid multiple calls of a single instruction... It seems like there's something surviving, not about the observable because RxJS automatically unsubscribes after conditions are met but about the function or the component itself (?)... – kfa Jun 20 '16 at 09:24
  • A global provided service is provided only once and if you execute code in the constructor then it is only executed once. This doesn't need to use `Observable`. – Günter Zöchbauer Jun 20 '16 at 09:26
  • That's exactly the behaviour I was expecting but it's not :/ wait until I get plnkr working @GünterZöchbauer – kfa Jun 20 '16 at 09:39

0 Answers0