Search code examples
javascriptangularobservablebehaviorsubject

BehaviorSubject issue, next() not working


I'm trying to use an angular service to store and communicate data through observable.

Here is my service

public _currentLegal = new BehaviorSubject({
  name: 'init',
  _id: 'init',
  country: 'init',
  city: 'init',
});
readonly currentLegal$ = this._currentLegal.asObservable();

constructor(private http: HttpClient) {
}

setCurrentLegal(legal) {
  const legaltest = {
    name: 'test',
    _id: 'test',
    country: 'test',
    city: 'test',
  }
console.log('emitting next value from', legal.name)
this._currentLegal.next({ ...legaltest });
}

I got a component that call setCurrentLegal, the console.log is triggered and correct. I then navigate to another component which subscribe to the currentLegal$ observable and the value is still the same (init) !

I tried accessing the value directly by setting public type and using getValue(), same. I tried duplicating the object as to not pass a reference, did not change anything.

Here is my subscripting component ngOnInit :

ngOnInit(): void {
  this.legalToUpdate = this.legalService.currentLegal$.subscribe((legal) => {
    console.log(legal)
  })
}

What's wrong here ? Thanks


Solution

  • You have this behavior because you use it in different modules and it is created a different instances.

    Put your service to be provide in root:

    @Injectable({ providedIn: 'root' })
    export class LegalService implements HttpInterceptor { }