首页 文章

在Angular 7中取消订阅Observable的简单方法

提问于
浏览
0

我有一个实现,当使用 takeUntil 销毁组件时,它会自动取消订阅Observables . 但是在许多组件中实现相同的代码很烦人 .

I want to know if this could be simplified (我不能使用 async 管道,因为我需要在Typescript组件中发出的值)

这是我目前的实施:

export class Component implements OnDestroy {
    _dstr = new Subject();

    data$: Observable<any> = this.store.select(Selector.getData);

    constructor(
        private store: Store<State>,
    ) {
        this.store.pipe(
            select(Selector.getOtherData),
            takeUntil(this._dstr),
        ).subscribe(data => {
            console.log('here is my data!', data)
        });
    }

    public ngOnDestroy(): void {
        this._dstr.next();
        this._dstr.complete();
    }

}

1 回答

  • 1

    您可以收集数组中的所有订阅,并取消订阅ngOnDestroy函数中的每个订阅 . 如果您经常需要这种行为,可以考虑使用一个抽象类,从中扩展所有组件,从中为您执行此操作 .

    import { Component, OnDestroy, OnInit } from '@angular/core';
    import { Subscription, Observable, of } from 'rxjs';
    
    export abstract class BaseComponent implements OnDestroy{
      public subscriptions: Subscription[] = [];
    
      public ngOnDestroy(): void {
        console.log("destroyed");
        this.subscriptions.forEach(s => s.unsubscribe());
      }
    }
    
    @Component({
      selector: 'my-app',
      templateUrl: './app.component.html',
      styleUrls: [ './app.component.css' ]
    })
    export class AppComponent {
    
    }
    
    let count: number = 0;
    @Component(
      {
        selector: 'app-derived',
        template: 'Derived Class'
      }
    )
    export class DerivedComponent extends BaseComponent implements OnInit, OnDestroy {
      private store: Observable<any> = of(count++);
      constructor() {
        super();
      }
      public ngOnInit(): void {
        this.subscriptions.push( this.store.subscribe(data => console.log(data)) );
      }
    }
    

    Blitzstack演示:https://stackblitz.com/edit/angular-peyoac

相关问题