【问题标题】:With Angular Directives, do Service subscriptions need to be unsubscribed?使用 Angular 指令,是否需要取消订阅服务?
【发布时间】:2020-12-22 18:31:44
【问题描述】:

使用 Angular 10,我有一个监听服务的指令。在这种情况下,我是否需要取消订阅该 Observable?

例如:

@Directive({
    selector: '[appShowFoo]'
})
export class ShowFooDirective {
    @HostBinding('class.foo') foo: boolean;

    constructor(private _fooService: FooService) {
        this._fooService.foo$.subscribe(foo => this.foo = foo);
    }
}

【问题讨论】:

    标签: angular angular-directive


    【解决方案1】:

    总是退订。活动订阅会占用内存,如果不清理会导致内存泄漏,而不是在您使用它们的地方。

    这样的事情会在可观察到的完成后清除订阅。

    const sub = this.observable$.subscribe(
        value =>{...}, 
        error => {...}, 
        /*onComplete*/
        () => sub.unsubscribe()
    );
    
    

    对于一次性操作,您只需致电toPromise() 并使用thenawait

    【讨论】:

      猜你喜欢
      • 2017-05-12
      • 2023-04-09
      • 2019-01-31
      • 2018-07-23
      • 2018-10-06
      • 2018-07-09
      • 2020-12-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多