除了异步管道,还有另一种自动订阅/取消订阅可观察的方法吗?

时间:2020-04-12 04:34:04

标签: angular rxjs

我想知道是否还有另一种自动从可观察对象进行订阅/取消订阅的方法?我主要在html模板中看到过异步管道,但是当我想在我的组件类中做某事时呢,比如说当您在角度项目中工作时。

3 个答案:

答案 0 :(得分:3)

我建议使用以下一种取消订阅方法:

  1. async pipe
  2. 使用takeUntil运算符:
@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit, OnDestroy {
  private readonly componentDestroyed$ = new Subject();

  ngOnDestroy(): void { this.componentDestroyed$.next() }

  ngOnInit(): void {
    myObservable$.pipe(takeUntil(this.componentDestroyed$)).subscribe(() => {
      // your code here...
    })
  }
}

  1. 使用subsink帮助您管理订阅
  2. 使用基于装饰器的方法,例如对于角度<9的ngx-auto-unsubscribe或对于角度> = 9的until-destroy

答案 1 :(得分:1)

您可能可以创建一个基类来这样做,并用您的组件类对其进行扩展,那么您不必为所创建的每个组件重复ngDestory处理。

 export class BaseComponent implements OnDestroy {
    public _subscriptions: Subscription[] = [];

    addSubscription(...sub): Subscription | Subscription[] {
        this._subscriptions.concat(sub);
        return sub;
    }

    ngOnDestroy(): void {
        this._subscriptions.forEach(s =>
            s.unsubscribe()
        );
    }
}

示例用法

class MyComp extends BaseComponent{
    ngOnInit(){
        this.addSubscription(interval(1000).subscribe())
    }
}

答案 2 :(得分:0)

您可以利用这样的行为主题

    import { Component, OnInit, OnDestroy } from '@angular/core';
    import { Subject } from 'rxjs';
    import { takeUntil } from 'rxjs/operators';
    export class ComponentA implements OnInit, OnDestroy {
     private componentUnload$ = new Subject<boolean>();

       constructor(
        public dataService: DataService,
      ) {}


        ngOnInit() {
        this.dataService.items$ // here, you are calling an observable
          .pipe(takeUntil(this.componentUnload$))
          .subscribe(items => {
            this.items = items;
          });
      }

      ngOnDestroy(): void {
        this.componentUnload$.next(true);
      }