【问题标题】:is there another way to auto subscribe /unsubscribe to an observable than async pipe?除了异步管道,还有另一种自动订阅/取消订阅可观察对象的方法吗?
【发布时间】:2020-07-24 18:33:38
【问题描述】:

我想知道是否有另一种方法可以自动订阅/取消订阅 observable?我主要在 html 模板中看到过异步管道,但是当我想在我的组件类中做某事时,比如谈论你在 Angular 项目中工作时的情况。

【问题讨论】:

  • "auto unsubscribe" 在 observable 完成时发生。所以这取决于你的观察。你有一个永远不会完成的无尽流吗?然后你必须取消订阅,或者通过pipe(takeWhile(() -> contition)) or pipe(takeUntil(observable) 完成它,或者只是取消订阅。如果您因为“httpClient”Observables 而问您问题,休息调用的结果请看这里:stackoverflow.com/questions/35042929/…

标签: angular rxjs


【解决方案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】:

    你可以利用这样的行为主体

        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);
          }
    

    【讨论】:

      【解决方案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. 使用基于装饰器的方法,例如 ngx-auto-unsubscribe 用于 angular until-destroy 用于 angular >= 9

      【讨论】:

      • 我在我的项目中使用 subsink 来解决这个问题,效果很好。
      猜你喜欢
      • 2021-06-14
      • 2021-08-07
      • 2016-07-10
      • 2019-11-15
      • 2020-06-28
      • 2019-05-06
      • 1970-01-01
      • 2019-10-23
      • 2022-01-23
      相关资源
      最近更新 更多