Search code examples
angularobservablebehaviorsubject

Angular BehaviorSubject returns initial value when subscribing after setting next value


I do have the following service:

export class TestService {

  constructor() { }

  private _schema = new BehaviorSubject("User");
  currentSchema = this._schema.asObservable();

  setSchema(schema: string) {
    this._schema.next(schema);
  }
}

When i subscribe to the observable and change the value after subscribing, everything works fine, but when i do subscribe in another component AFTER changing the value, i receive the inital value intead of the new set value.

So when i subscribe to the observable in ngOnInit() and setting a next value in the same component, it works. But i want to receive that next value in another component which is created later.

I am using the service like this:

ngOnInit() {

    this.testService.currentSchema.subscribe(x => {
      console.log('DETAIL >> ' + x);
    });
}

I have no clue why this is happening, as the sense of BehaviorSubjects is getting the value even after subscribing.


Solution

  • The problem seemed to be in the component itself. I never though of that being a problem of the component, so i tried everything from creating new services, a whole new testapp etc.

    When i tried to create a new component to use the service there, it worked. I could not really figure out what was causing the issue in the old component, i just copied the code 1 to 1 to the new component, but it worked all of a sudden.