在 Angular v16 中,使用 takeUntillDestroy 或 toSignal 取消订阅 Obserable 我应该做什么

问题描述 投票:0回答:1

Assalam Alikum 和大家好... 在我的角度应用程序中,我有太多 api 链接无法与后端对话 我的大部分服务都是这样的 在服务内部

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

从我的文章中我简单地称它为

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

当取消订阅时,我曾经有一个我实现并使用它来取消订阅的组件, 然而,即使在我的新应用程序中,我想使用

toSignal()
takeUntillDestroy
, 你认为什么更好?我应该在每个函数中继续调用 takeuntilldestory 吗?或者如何使用 toSignal

我尝试过

destoryRef = inject(DestroyRef)
在我的函数中
this.myservice.getData().pipe(takeUntillDestroy()).subscribe
它似乎有效,但仍然不确定这是否是最好的方法

angular rxjs signals unsubscribe
1个回答
0
投票

toSignal
依赖于与
toUntilDestroyed
相同的机制:
DestroyRef
,所以基本上是相同的。

因此,为了便于阅读,建议使用

toSignal

© www.soinside.com 2019 - 2024. All rights reserved.