Not able to get Observable value into other modules component using shared services

318 views Asked by At

Please check this GitHub repo https://github.com/nileshzala005/Service-demo

userService registered at root level.

I would like to get getUserLogin observable value into SharedModule's UserComponent. When user clicks on the button Send value to user component from the HomeComponent that is declared in the HomeModule.

UserService at the root level:

userLogin = new Subject<string>();

  constructor() { }
  sendUserLogin(user: string) {
    console.log("value received at user service ", user);
    this.userLogin.next(user);
  }
  getUserLogin(): Observable<string> {
    return this.userLogin.asObservable();
  }

HomeComponent in the HomeModule:

export class HomeComponent implements OnInit {

  constructor(private userService: UserService) {

  }

  ngOnInit() {
  }
  onClick() {
    console.log("value is send from home component", "Nilesh")
    this.userService.sendUserLogin("Nilesh");
  }

}

UserComponent in SharedModule:

export class UserComponent implements OnInit {

  constructor(private userService: UserService) { }

  ngOnInit() {
    this.userService.getUserLogin().subscribe(res => {
          /// here it should receive but not able to get it
      console.log("user component should get value here ", res);
    });
  }

}

console log

2

There are 2 answers

0
Faisal Choura On

You would need to use a BehaviorSubject instead of a Subject to get the value emitted. Check this post for explanation. Syntax is a bit out dated but it still follows the same concept

What is the difference between Subject and BehaviorSubject?

0
igor_c On

Try to use BehaviorSubject instead of Subject. It'll send the last value to the subscription even if the subscription was done after the value was emitted.

Could be a problem that you subscribe after the value is emitted.