0

I am able to get the '0' value in my componenet2 but not the next value which this.navItem$ has under UserService

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

           @Injectable()
            export class UserService {
             constructor() {}

                 // Observable navItem source
                 public _navItemSource = new BehaviorSubject(0);

                // Observable navItem stream
                navItem$ = this._navItemSource.asObservable();

                // service command
                      changeNav(number) {
                      this._navItemSource.next(number);
                      console.log(this._navItemSource.getValue())
                      console.log(this.navItem$)
                }
          }`

The service I am using is as follows

      `export class Component1{
             constructor(private _userService: UserService)
             fun(){
             this._userService.changeNav(this.notificationslist)
             }
        }`

And in my another component where I want to check values from the service

          `  export class Component2{
             ngOnInit() {
               this.subscription = this._userService.navItem$
               .subscribe(item => this.item1 = item)
                console.log(this.subscription)
                console.log(this.item1)
               }
            }`

My issue is when I subscribe I get the following data on console
I only get the initial value '0' but not the next changed value,
how can I check last value or a particular value from the array which has changed from say for an example "Status:Inprogress" to "Status:Success" each and everytime I open component2 because depending upon that status I have to show and hide some elements

Enthu
  • 512
  • 2
  • 13
  • 38

1 Answers1

0

I think this should be helpful, there are umpteen no. of answers for this same scenario but we generally do not pay attention to the details of the answer and the issue which I have posted is the same which others have already faced. We should not use providers: [xyzservice] in each component, instead it should be only on the higher root component. There are already answers to it in the links below:

Angular2 + RxJS BehaviorSubject subscription not working on all components

Angular2: subscribe to BehaviorSubject not working

Angular2 Observable BehaviorSubject service not working

Enthu
  • 512
  • 2
  • 13
  • 38