Angular RxJS Subject 订阅和取消订阅

Angular RxJS Subject subscription and unsubsciption

我有一个组件可以从 API link 获取更新,但是当组件被销毁时 API 调用不会停止。我正在使用一个主题来这样做,我退订了它。我的 api 服务是

public getupdate(){
  return this.httpClient.get(this.serverGetUpdate)
}

我已经在我的组件中订阅了这项服务,并希望每 3 秒获取和更新一次,我确实收到了更新。这是我的代码。

export class InprogressComponent implements OnInit, OnDestroy{


subject=new Subject()
  constructor(private apiservice: ApiService) {
    
   }
  
  ngOnInit(): void {
    
    this.getupdate()
  }
  getupdate(){
    this.subject.subscribe(x=>{timer(0,3000).pipe(switchMapTo(this.apiservice.getupdate()),takeWhile(x=>x["data"]=="Something")).subscribe(console.log)})
    this.subject.next()
  }

  

  ngOnDestroy(): void {
    //this.subject.next()
    this.subject.unsubscribe()
  }

}

我是 RxJS 的新手,我不明白为什么 API 调用在取消订阅后不会停止。我也愿意接受其他建议。谢谢

试试这个

export class InprogressComponent implements OnInit, OnDestroy{

 dataSubscription: Subscription = new Subscription();

  ngOnInit(): void {

    this.getupdate()
  }
  getupdate() {
   this.dataSubscription = interval(3000).subscribe(() => {
     console.log('here');
   })
  }



  ngOnDestroy(): void {
    this.dataSubscription.unsubscribe()
  }

}

Unsubscribe nulls the internal array of subscriptions in the Subject, it does not unsubscribe the subject from it's source

 dataSubscription: Subscription;

  getupdate(){
    this.dataSubscription = this.subject.subscribe(x=>{timer(0,3000).pipe(switchMapTo(this.apiservice.getupdate()),takeWhile(x=>x["data"]=="Something")).subscribe(console.log)})
    this.subject.next()
  }

  

  ngOnDestroy(): void {
    this?.dataSubscription.unsubscribe()
  }

但布赖恩斯上面的回答是一种更简洁的方式来实现您的功能。

这样试试:

export class InprogressComponent implements OnInit, OnDestroy{

 unsubscribe: Subject<void> = new Subject();

  ngOnInit(): void {

    this.getupdate()
  }
  getupdate() {
   this.apiService
      .getupdate()
      .pipe(takeUntil(this.unsubscribe))
      .subscribe(
        data => {
          // do your operation
        },
        error => {
         // error operation
        }
      );
  }



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

}