Angular/RxJs When should I unsubscribe from `Subscription`

前端 未结 22 2706
隐瞒了意图╮
隐瞒了意图╮ 2020-11-21 04:56

When should I store the Subscription instances and invoke unsubscribe() during the NgOnDestroy life cycle and when can I simply ignore them?

22条回答
  •  孤城傲影
    2020-11-21 05:32

    I tried seangwright's solution (Edit 3)

    That is not working for Observable that created by timer or interval.

    However, i got it working by using another approach:

    import { Component, OnDestroy, OnInit } from '@angular/core';
    import 'rxjs/add/operator/takeUntil';
    import { Subject } from 'rxjs/Subject';
    import { Subscription } from 'rxjs/Subscription';
    import 'rxjs/Rx';
    
    import { MyThingService } from '../my-thing.service';
    
    @Component({
       selector: 'my-thing',
       templateUrl: './my-thing.component.html'
    })
    export class MyThingComponent implements OnDestroy, OnInit {
       private subscriptions: Array = [];
    
      constructor(
         private myThingService: MyThingService,
       ) { }
    
      ngOnInit() {
        const newSubs = this.myThingService.getThings()
            .subscribe(things => console.log(things));
        this.subscriptions.push(newSubs);
      }
    
      ngOnDestroy() {
        for (const subs of this.subscriptions) {
          subs.unsubscribe();
       }
     }
    }
    

提交回复
热议问题