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);
});
}
}
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?