英文:
How can I unsubscribe from a any var observable in angular when component is destroyed?
问题
@Input()
var: any;
var 被传递为一个 observable,但是当 ngDestroyed 被调用时,我得到了一个 var.unsubscribe() 不是一个函数的错误。
我尝试了 var.unsubscribe(),但不起作用。
英文:
@Input()
var:any;
var passed as an observable but I'm getting a var.unsubscribe() is not a function when ngDestroyed is called.
I tried var.unsubscribe() and is not working
答案1
得分: 2
在模板中使用 async
管道,尽量避免在组件内部进行订阅。如果必须在组件内订阅(.ts 文件),请使用以下方法进行取消订阅。不要在服务中这样做!
export class MyComponent {
private readonly onDestroy = new Subject<void>();
products$: Observable<Product>;
constructor(private myService: MyService) { }
ngOnInit(): void {
// 正确的方式
// 不要忘记在模板中使用 async 管道
this.products$ = this.myService.getMyProducts();
// 不是最佳方式
this.myService.getMyProducts().pipe(
takeUntil(this.onDestroy),
tap((products: Product) => {
// 进行你的操作
})
).subscribe()
}
ngOnDestroy() {
this.onDestroy.next();
this.onDestroy.complete();
}
}
希望这对你有帮助!
英文:
Use the async
pipe inside the template and avoid (as much as possible) subscribing inside the component.
if you must subscribe inside the component (.ts file) use the following approach for unsubscribing. don't do that inside services!
export class MyComponent {
private readonly onDestroy = new Subject<void>();
products$: Observable<Product>;
constructor(private myService: MyService) { }
ngOnInit(): void {
// the right way
// don't forget to use the async pipe inside the template
this.products$ = this.myService.getMyProducts();
// not the best way
this.myService.getMyProducts().pipe(
takeUntil(this.onDestroy),
tap((products: Product) => {
// do your staff
})
).subscribe()
}
ngOnDestroy() {
this.onDestroy.next();
this.onDestroy.complete();
}
}
答案2
得分: 1
这是一个相当通用的问题,你可以在谷歌上找到类似的内容,比如这篇文章 https://www.digitalocean.com/community/tutorials/angular-takeuntil-rxjs-unsubscribe
你可以采用以下方式之一:
var.pipe(takeUntil(this.unsubscribe$)).subscribe()
或者你可以将它分配给订阅:
this.sub = var.subscribe()
然后在 onDestroy 中执行:
this.sub.unsubscribe();
无论哪种方式,这篇文章都有很好的示例。
英文:
it's a pretty generic issue, you can find anywhere in google, like this article https://www.digitalocean.com/community/tutorials/angular-takeuntil-rxjs-unsubscribe
you can either do stuff like
var.pipe(takeUntil(this.unsubscribe$)).subscribe()
or you can assign it to subscriptions
this.sub = var.subscribe()
then later on in onDestroy do
this.sub.unsubscribe();
either way this article have good examples
答案3
得分: 1
你不会“取消订阅”一个“observable”,而是一个“subscription”。Observables
是惰性的
,除非你对它们进行订阅
,否则它们不会触发。你可以简单地对一个observable
进行订阅
,并将其存储在一个变量中,然后在该变量上调用.unsubscribe()
。
这是一个不错的阅读材料。
英文:
You do not unsubscribe
an observable
, but a subscription
. Observables
are lazy
, unless you subscribe
to them, they won't fire. You can simply subscribe
to an observable
, and store it in a variable. then call .unsubscribe()
on that variable.
This is a good read
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论