0

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

  • You're not using your `UserComponent` anywhere in your github example. Your code works if you actually create an instance of your `UserComponent` e.g by adding it to your `app.component.html`. See: https://stackblitz.com/edit/github-mz7lqy – frido Dec 05 '19 at 11:40
  • @fridoo Thanks. It's working – Zala Nilesh Dec 06 '19 at 14:43

2 Answers2

1

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?

Faisal Choura
  • 170
  • 1
  • 8
0

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.

igor_c
  • 1,200
  • 1
  • 8
  • 20