In Angular v16 unsubscribe from an Obserable using takeUntillDestroy or toSignal what should I do

48 Views Asked by At

In my Angular application I have too many api links to talk with backend. Most of my services are like that. Inside a service:

getData():Obserable<any>{
return this.http.get('myapli/get/data/any')
}

and from my component I simply call it :

this.mysrvice.getData().subscribe({next:res=>log('res')})

when unsubscribing from it I used to have a component that I implement and use it to unsubscribe, however in my new application I want to use eaither toSignal() or takeUntillDestroy, what do you think is better? Should I keep calling takeuntilldestory in every function? or how to use toSignal?

I tried to destoryRef = inject(DestroyRef) and in my function this.myservice.getData().pipe(takeUntillDestroy()).subscribe and it seemed to work, but still not sure if it was best approach.

2

There are 2 best solutions below

1
Matthieu Riegler On

toSignal relies on the same mecanism as toUntilDestroyed : DestroyRef, so basically it's the same.

So for the sake of readability, toSignal would be recommended.

1
Walter Mauch On

In a component, you should prefer toSignal(). It automatically unsubscribes and updates the Dom tree when the service emits a new value. You can use it like this:

const data = toSignal(this.myService.getData())

In your template, you can then access your signal as a function

{{ data() }}