【问题标题】:Angular RxJS Subject subscription and unsubsciptionAngular RxJS 主题订阅和取消订阅
【发布时间】:2021-06-28 02:37:21
【问题描述】:

我有一个组件可以从 API 链接获取更新,但是当组件被销毁时 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 调用没有停止。我也愿意接受其他建议。谢谢

【问题讨论】:

  • 您是否在 ngOnDestory 上运行控制台日志以确保它被调用?另外你为什么要在销毁时调用 .next()?
  • 我很抱歉 .next() 被注释掉了(现在编辑)。我看到在销毁后正在从后端调用 API。
  • 我的意思是调用了 ngOnDestory。需要确保组件被销毁。如果你把console.log('destroyed') 找出来。
  • @BrianSmith 是的,它被破坏了,我在控制台上被“破坏”了

标签: angular rxjs observable


【解决方案1】:

试试这个

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()
  }

}

【讨论】:

  • 谢谢。这适用于我的问题。你能解释一下为什么主题退订不起作用。
  • 如果不亲自运行,很难准确判断。但看起来主题确实被正确取消订阅了。但是被启动的定时器和定时器之后的下游进程并没有停止,只有主题。
【解决方案2】:

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()
  }

但上面的 Brians 回答是实现您的功能的一种更简洁的方式。

【讨论】:

    【解决方案3】:

    试试这样:

    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();
      }
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-18
      • 1970-01-01
      • 2019-01-24
      • 1970-01-01
      • 2020-02-14
      • 2020-09-20
      • 2018-08-14
      • 2021-03-03
      相关资源
      最近更新 更多