Angular 如何销毁行为主体

Angular 如何销毁行为主体,angular,typescript,behaviorsubject,Angular,Typescript,Behaviorsubject,您正在使用BehaviorSubject在组件之间交换和执行函数 我的问题是BehaviorSubject函数总是在执行,而事实上,我只是希望根据我的操作来执行它们 我做错什么了吗?我怎么解决这个问题,有人能帮我吗 我试过的 TComponent.ts subscription: Subscription; ngOnDestroy() { this.subscription.unsubscribe(); } this.subscription = this.taskprof

您正在使用BehaviorSubject在组件之间交换和执行函数

我的问题是BehaviorSubject函数总是在执行,而事实上,我只是希望根据我的操作来执行它们

我做错什么了吗?我怎么解决这个问题,有人能帮我吗

我试过的

TComponent.ts

 subscription: Subscription;

  ngOnDestroy() {
    this.subscription.unsubscribe();
}

  this.subscription = this.taskprofileService.dataTask.pipe(filter(y => !!y)).subscribe(y => {
      this.pauseTimer(y);
    });

    this.subscription = this.taskprofileService.timerInfo.pipe(filter(x => !!x)).subscribe(x => {
      this.sendInfo(x);
    });
您可以在Ngondestory中使用“取消订阅”,如下所示。 使用主体而不是主体行为 .ts文件 认购:认购

  this.subscription = this.taskprofileService.dataTask.pipe(filter(y => !!y)).subscribe(y => {
      this.pauseTimer(y);
    });

    this.subscription = this.taskprofileService.timerInfo.pipe(filter(x => !!x)).subscribe(x => {
      this.sendInfo(x);
    });

ngOnDestroy() {
    this.subscription.unsubscribe();
}
服务文件

使用Subject尝试以下方法。
更多信息,请回答您的问题-@SameerKhan谢谢您的帮助。我看过这篇文章,但我无法应用它,我有很多疑问,而且它对我尝试的内容没有作用:当你实现建议的答案时,你会遇到什么错误@MatSigh@PushprajsinhChudasama我的第一个疑问是在哪里应用这个。我必须将此应用于TaskProfile服务,对吗?你能给我一些建议吗?我不知道我是否正确理解你,但也许你应该用主语而不是行为主语。Behavior subject的工作原理是,您始终可以从开始订阅中获得价值,因此执行停止功能的消息始终必须至少运行一次。感谢您的帮助,我认为应该向subject提供我想要的建议。所以我不再需要使用构造函数了?如果答案对你有帮助,请接受。很高兴帮助你@Matsighn尚未工作,此.taskService.currentTaskInfo以未定义状态到达,今晚将为您提供stackblitz@Matsight问题在于,使用Subject时,SendTimerInfo事件函数{this.currentTaskInfo.next event;}未发送数据:
import { Observable, Subject } from 'rxjs';
  public dataTask = new Subject<any>();

  public timerInfo = new Subject<any>();
  StopTimerInfo(taskInfo){
      this.dataTask.next(taskInfo);
  }

  SendTimerInfo(taskInfo){
      this.timerInfo.next(taskInfo);
  }