Mateusz Witkowski
Mateusz Witkowski

Reputation: 1746

Angular 2 fail to subscribe with shared service

I have some issues with BehaviorSubject. Here's shared service for three components:

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';

@Injectable()
export class StageEndService {

  private stageNumber = new BehaviorSubject<number>(0);
  private stageNumberPassed = new BehaviorSubject<number>(0);

  stageNumber$ = this.stageNumber.asObservable();
  stageNumberPassed$ = this.stageNumber.asObservable();

  announceStageNumber(num) {
    this.stageNumber.last(num);
  }

  announceStageNumberPassed(num) {
    this.stageNumberPassed.last(num);

  }
}

Here's first part of one of the two components that changes values in service:

import { StageEndService } from './../../../common/services/stage-end.service';

@Component({
...
providers: [StageEndService]
})

...
private value = 6;

constructor (private stageEndService: StageEndService) {

  this.stageEndService.announceStageNumber(value);

}

Second component is similar, but changes value of stageNumberPassed.

In my last component I'm trying to subscribe but fail (console.log returns 0):

import { StageEndService } from './../../../common/services/stage-end.service';

// there's no provider here since it's not necessary if I'm correct

 constructor(private stageEndService: StageEndService) {}

ngOnInit() {
  this.stageNumberSubscription = this.recruitmentEndService.stageNumber$.subscribe(response => {
  this.stageNumber = response;
});

No idea where's the problem. When I log values passed to function in service it returns correct numbers. Don't know if that matters but just in case: last component (where I'm trying to subscribe) is grand-grandchildren of the first component where I'm setting new value for the first time.

Upvotes: 1

Views: 716

Answers (2)

micronyks
micronyks

Reputation: 55443

this.recruitmentEndService.stageNumber$.subscribe(response => {
  this.stageNumber = response;
});

should be

this.stageEndService.stageNumber$.subscribe(response => {
  this.stageNumber = response;
});

Upvotes: 1

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657158

Don't add the service to providers of each component. This way each component gets its own instance and you can't use it to communicate between services.

Only provide the service once in the AppModule or a shared parent component.

Upvotes: 3

Related Questions