Angular 2 - 使用 BehaviorSubject 创建循环的服务

Angular 2 - Service with BehaviorSubject creating a loop

我有一个嵌套组件,其中包含一个可点击的图表,其中包含三个可选部分,这些部分将设置它所在的 md-tab-group 的 selectedIndex。我点击第一个,转到第一个选项卡,然后转到第二个导致第二个和第三个选项卡,非常简单。

问题是我正在使用的服务似乎正在创建某种循环。当我控制服务正在执行的步骤时,我发现它每次都在变大。

相关服务代码:

  changeActiveTab(number) {
    console.log("Before: ");
    this._activeTab.subscribe(val => console.log(val));
    this._activeTab.next(number);
    console.log("After");
    this._activeTab.subscribe(val => console.log(val));
  } 

当我点击第一部分时看到的内容,使用主导航导航回到图表,然后再重复该过程两次:

Before:
0
1
After
1
Before:
1
2
2
2
After:
2
Before:
2
3
3
3
3
3
3
After
3

我是 BehaviorSubject 的新手,知道我哪里出错了吗?

(我使用的示例来自 here 如果有帮助的话)

父组件相关代码:

 selectedTab: number;
  subscription:Subscription;
  constructor( private _activeTabService: ActiveTabService) { }

  ngOnInit() {
    this.subscription = this._activeTabService.activeTab$.subscribe(
        selectedTab => this.selectedTab = selectedTab);
  }

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

子组件的相关图表 TS:

  onClick(event){
    if(event.series == 'Table'){
      this.changeActiveTab(1);
    }
    if(event.series == 'Chairs'){
      this.changeActiveTab(2);
    }        
    if(event.series == 'Desks'){
      this.changeActiveTab(3);
    }
  }

你是对的。 changeActiveTab 确实会在每次调用时创建越来越多的订阅。 该服务不应进行订阅。 该服务应该有两种方法。 1. setTab - 将使用相关参数调用 subject.next。 2 注册 - return 该主题的可观察值。

例子:

export class tabService {
subject  = new Subject(); 
setTab(value: string)
   this.subject.next(value);
}

registerTab(){
return this.subject.asObservable();
}

在我的组件中:

myfunction(){
   this.tabService.registerTab().subscribe(
   (res) => do what you want with this value....
);

changeTab(value: string)
{
   this.tabService.setTab(value);
}