How to implement ngOnDestroy() correctly in Angular?

前端 未结 2 499
别那么骄傲
别那么骄傲 2021-01-14 14:42

I have a child component with a timer, every 2 second I send api call to the server. I need to do this call as long as the user is on the page even if he/she going to a wedd

2条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-14 15:18

    Hmm.. You can try using RxJS's takeUntil operator instead.

    First and foremost, you import takeUntil and Subject into your component.

    import { takeUntil, mergeMap } from 'rxjs/operators';
    import { Subject } from 'rxjs/Subject'
    

    Next,

    unsubscribe: Subject = new Subject();
    

    And then,

    this.myTimer
      .pipe(
        mergeMap(this.myService.doSomeWork(this.myId)),
        takeUntil(this.unsubscribe)
      ).subscribe((data) => {
        this.myData = data;                
      }, (errRes)=>{
        console.log(errRes);
      });
    

    Do take note that takeUntil must be the last operator on your pipe() to prevent any observables from 'leaking' out.

    And on your ngOnDestroy,

    ngOnDestroy() {
      this.unsubscribe.next();
      this.unsubscribe.complete();
    }
    

提交回复
热议问题