I have a child component with a timer, every 2 second I send api call to the server. I need to do this call as long as the user is on the page even if he/she going to a wedd
Hmm.. You can try using RxJS's takeUntil operator instead.
First and foremost, you import takeUntil and Subject into your component.
import { takeUntil, mergeMap } from 'rxjs/operators';
import { Subject } from 'rxjs/Subject'
Next,
unsubscribe: Subject = new Subject();
And then,
this.myTimer
.pipe(
mergeMap(this.myService.doSomeWork(this.myId)),
takeUntil(this.unsubscribe)
).subscribe((data) => {
this.myData = data;
}, (errRes)=>{
console.log(errRes);
});
Do take note that takeUntil must be the last operator on your pipe() to prevent any observables from 'leaking' out.
And on your ngOnDestroy,
ngOnDestroy() {
this.unsubscribe.next();
this.unsubscribe.complete();
}