How to cancel a subscription in Angular2

后端 未结 8 1551
忘了有多久
忘了有多久 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 02:04

    I prefer personally to use a Subject to close all subscriptions a component might have at the destroy life cycle step which can be achieved this way :

    import { Component} from '@angular/core';
    import { Subject } from "rxjs/Rx";
    
    @Component({
      selector:    'some-class-app',
      templateUrl: './someClass.component.html',
      providers:   []
    })
    
    export class SomeClass {  
    
      private ngUnsubscribe: Subject = new Subject(); //This subject will tell every subscriptions to stop when the component is destroyed.
    
      //**********
      constructor() {}
    
      ngOnInit() {
    
        this.http.post( "SomeUrl.com", {}, null ).map( response => {
    
          console.log( "Yay." );
    
        }).takeUntil( this.ngUnsubscribe ).subscribe(); //This is where you tell the subscription to stop whenever the component will be destroyed.
      }
    
      ngOnDestroy() {
    
        //This is where we close any active subscription.
        this.ngUnsubscribe.next();
        this.ngUnsubscribe.complete();
      }
    }
    

提交回复
热议问题