av0000
av0000

Reputation: 1967

Angular 2 - Service with BehaviorSubject creating a loop

I have a nested component that contains a clickable chart with three selectable sections that will set the selectedIndex of the md-tab-group that it is in. I click on the first, I go to first tab, the second leads to the second, and third the third tab, pretty straightforward.

The problem is that the service I'm using seems to be creating some sort of loop. When I console the steps the service is taking I see it getting bigger every time.

Relevant Service code:

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

What I see when I click on the first section, navigate back to the chart with the main nav, and repeat the process two more times:

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

I'm pretty new to BehaviorSubject's, any ideas of where I'm going wrong?

(My example that I used was from here if that helps any)

Relevant code for parent component:

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

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

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

Relevant Chart TS for the child component:

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

Upvotes: 1

Views: 1301

Answers (1)

Avi
Avi

Reputation: 1964

you are right. changeActiveTab does create more and more subscription on every call. the service should not make the subscription. the service should have two methods. 1. setTab - will call subject.next with the relevant parameter. 2 register - return an observable of that subject.

exmaple:

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

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

in my component:

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

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

Upvotes: 2

Related Questions