How to cancel a subscription in Angular2

后端 未结 8 1544
忘了有多久
忘了有多久 2020-11-30 01:37

How does one cancel a subscription in Angular2? RxJS seems to have a dispose method, but I can\'t figure out how to access it. So I have code that has access to an EventEm

8条回答
  •  爱一瞬间的悲伤
    2020-11-30 01:59

    The recommended approach is to use RxJS operators such as the takeUntil operator. Below is the code snippet showing how to use it :-

    import { Component, OnInit, OnDestroy } from '@angular/core';
    import { interval, Subject } from 'rxjs';
    import { takeUntil } from 'rxjs/operators';
    
    @Component({
        selector: 'app-root',
        templateUrl: './app.component.html'
    })
    export class AppComponent implements OnInit, OnDestroy {
        private ngUnsubscribe = new Subject();
    
        constructor() { }
    
        ngOnInit() {
            var observable1 = interval(1000);
            var observable2 = interval(2000);
    
            observable1.pipe(takeUntil(this.ngUnsubscribe)).subscribe(x => console.log('observable1: ' + x));
            observable2.pipe(takeUntil(this.ngUnsubscribe)).subscribe(x => console.log('observable2: ' + x));
        }
    
        ngOnDestroy() {
            this.ngUnsubscribe.next();
            this.ngUnsubscribe.complete();
        }
    }
    

    You can find a detailed explanation of the topic here

提交回复
热议问题