I've encountered some challenges with BehaviorSubject while using a shared service across 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);
}
}
The first of the two components modifying values in the service is shown below:
import { StageEndService } from './../../../common/services/stage-end.service';
@Component({
...
providers: [StageEndService]
})
...
private value = 6;
constructor (private stageEndService: StageEndService) {
this.stageEndService.announceStageNumber(value);
}
The second component, similar to the first one, changes the value of stageNumberPassed.
In the last component, my attempt to subscribe fails (the 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;
});
I'm unsure where the problem lies. When I log the values passed to the function in the service, it provides the correct numbers. It may be worth noting that the last component where I'm trying to subscribe is several levels down from the first component where I initially set the new value.