I am using a subject in rxjs
to pass data from my login component to the user-profile component but what happens is in my login component I call the sendUser
method in the login component then in the user-profile component I subscribe to the observable but the currentUserObj value is undefined when I console.log the value. Can someone please help me since I've been trying to fix this for hours? Thanks.
auth.service.ts
private userSource = new Subject<User>();
currentUser$ = this.userSource.asObservable();
sendUser(user: any) {
this.userSource.next(user);
}
login.component.ts
loginUser() {
this.user = {
email: this.email,
password: this.password,
};
this._auth.loginUser(this.user).subscribe(
(res) => {
this.token = res.access_token;
this.user = res.user;
localStorage.setItem('token', this.token);
this._auth.sendUser(this.user); // This is where I use the send user function in my auth service
this._router.navigate(['/profile']);
},
(err) => {
this.errorMessage = err.message;
}
);
}
user-profile.component.ts
constructor(private _auth: AuthService) {}
currentUserObj: {};
ngOnInit(): void {
this._auth.currentUser$.subscribe((user) => {
this.currentUserObj = user;
});
console.log(this.currentUserObj);
}