1

我有一个嵌套组件,其中包含一个可单击的图表,其中包含三个可选部分,这些部分将设置它所在的 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 很陌生,对我哪里出错有任何想法吗?

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

父组件的相关代码:

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

1 回答 1

2

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

示例:

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);
}
于 2017-04-05T19:54:49.807 回答