how to unsubscribe for an observable

前端 未结 2 1768
星月不相逢
星月不相逢 2021-01-17 04:03

I have an angular application where I am reading a file and processing it and this processing is part of observable. I have a service which returns the observable an (ngbus

2条回答
  •  一生所求
    2021-01-17 04:53

    This is a good approach using takeuntil and ngUnsubscribe

    private ngUnsubscribe: Subject = new Subject();
    
    ngOnInit() {
      this.myThingService
        .getThings()
        .takeUntil(this.ngUnsubscribe)
        .subscribe((things) => console.log(things));
      /* if using lettable operators in rxjs ^5.5.0
          this.myThingService.getThings()
              .pipe(takeUntil(this.ngUnsubscribe))
              .subscribe(things => console.log(things));
          */
      this.myThingService
        .getOtherThings()
        .takeUntil(this.ngUnsubscribe)
        .subscribe((things) => console.log(things));
    }
    ngOnDestroy() {
      this.ngUnsubscribe.next();
      this.ngUnsubscribe.complete();
    }
    

提交回复
热议问题