To avoid Observable memory leaks inside Components, I am using takeUntil() operator before subscribing to Observable.
I write something like this inside
I can see that you are subscribing to a http response. There is one important thing when using Angular HttpClient: You don't have to unsubscribe from it as it is done automatically!
You can test that using finalize operator - it is called when observable completes. (And when observable completes, it is automatically unsubscribed)
this.http
.get('test')
.pipe(takeUntil(this.unsubscribe$), finalize(() => console.log('I completed and unsubscribed')))
.subscribe((x) => console.log(x));
If you are worried that your component might die while the HTTP request is still on it's way, and that code in callback might still execute, you could do something like this:
private subscription: Subscription;
ngOnInit(): void {
this.subscription = this.http
.get('test')
.subscribe((x) => console.log(x));
}
ngOnDestroy(): void {
// Here you should also do a check if subscription exists because in most cases it won't
this.subscription.unsubscribe();
}
It is also worth checking the AsyncPipe
The AsyncPipe subscribes (and unsubscribes) for you automatically.