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
Well, observables are asynchronous patterns. They are based on push rather than pull strategy i.e. when they got data, they push data to the subscriber. Now, you must take caution while working with them as they continue to push data even when the component destroys. You need to explicitly unsubscribe from the observable. In ngOnDestroy() lifecycle hook you need this piece of code too.
this.myTimer.unsubscribe()
And that's it, you will not get more data. Alternatively, you can use takeWhile() or takeUntil() approach. Have a look- https://brianflove.com/2016/12/11/anguar-2-unsubscribe-observables/
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<void> = 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();
}