I created a loginComponent that is responsible for receiving an email and password from the user, then making an HTTP request to retrieve the user data. My goal is to utilize this user data in other components through a service.
Here is the login component:
onRecievingResults(value:loginInterface){
this.authService.saveData(value);
}
onLog(){
this.onRecievingResults(this.loginUser)
this.router.navigateByUrl('/stats/list')
}
The service implementation:
public currentUser:User | null = null;
private dataUserSource = new BehaviorSubject<User | null>(this.currentUser);
dataEmitter = this.dataUserSource.asObservable();
public saveData(value:loginInterface){
this.loginUser(value).subscribe()
this.dataUserSource.next(this.currentUser);
}
public loginUser(loginInterface: loginInterface | null){
const url = `${this.basicURL}/login`
const body = {email: loginInterface?.email, password1: loginInterface?.password1}
return this.http.post<loginResponse>(url, body)
.pipe(
map(({user, token}) => this.setAuthentication(token, user)),
catchError(err => throwError(() => err.error.message))
)
}
private setAuthentication( token:string, user: User){
this.currentState = authStatus.Authenticated
this.currentUser = user
localStorage.setItem('token', token)
console.log(this.currentUser) // Here i have the userData
return true
}
Additionl service I am using:
ngOnInit(): void {
this.authService.dataEmitter.subscribe(data => console.log(data))
}
public currentUser:User | null = null
The issue I am facing is that even though I can successfully fetch the User data within my service method, when I try to access it in my component after logging in, it returns "null". What could be causing this discrepancy?