角度:适当的退订时间 [英] Angular: Proper time to unsubscribe

查看:67
本文介绍了角度:适当的退订时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Web服务时,什么时候退订是最佳时间?在我的代码中,我一直在这样做

When using web services, when is the best time to unsubscribe? In my code I have been doing this

tempFunction() {
    const temp = this.myService.getById(id).subscribe(
        response => this.model = response,
        error => console.error(error),
        final => temp.unsubscribe() // unsubscribe here
    );
}

但是在其他任何地方,我都看到了

But everywhere else, I have seen this

temp: any;

tempFunction() {
    temp = this.myService.getById(id).subscribe(
        response => this.model = response,
        error => console.error(error),
        final => {}
    );
}

ngOnDestroy() {
    this.temp.unsubscribe(); // vs unsubscribe here
}

我的退订方式与其他所有人的退订方式有功能上的区别吗?

Is there a functional difference in how I am unsubscribing vs how everyone else is unsubscribing?

推荐答案

您不需要像简单的那样取消订阅简单的Web请求.他们只会解雇一次,并且会为您取消订阅. 这是一个SO问题,讨论了这个主题以及为什么它是不必要的.

You don't need to unsubscribe from a simple web request like you have. They only fire once and will take care of the unsubscribe for you. Here is a SO question that discusses this very topic and why it is unnecessary.

作为取消订阅的一般主题,最好的方法通常是使用此模式使用takeUntil.这样,您可以确保在以尽可能最干净的方式销毁组件时清理所有内容(而不必保留多个订阅并在每个订阅上调用unsubscribe).

As a general topic of how to unsubscribe, the best approach tends to be using this pattern of using takeUntil. This allows you to ensure that everything is cleaned up when your component is destroyed in the cleanest way possible (without having to hold onto multiple subscriptions and calling unsubscribe on each of them).

import { Subject } from 'rxjs/Subject';
import 'rxjs/add/operator/takeUntil';

@Component({ ... })
export class ExampleComponent implements OnInit, OnDestroy {
    destroy$: Subject<boolean> = new Subject<boolean>();

    ngOnInit() {
        this.someMethodThatReturnsObservable(...)
            .takeUntil(this.destroy$)
            .subscribe(...);

        this.someOtherMethodThatReturnsObservable(...)
            .takeUntil(this.destroy$)
            .subscribe(...);
    }

    ngOnDestroy() {
        this.destroy$.next(true);
        // Now let's also unsubscribe from the subject itself:
        this.destroy$.unsubscribe();
    }
}

这篇关于角度:适当的退订时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆