Issue
I have a loginComponent that receives an email and a password and makes an http request to get the user data. After that, I want to use that user data in other components using a service.
login component:
onRecievingResults(value:loginInterface){
this.authService.saveData(value);
}
onLog(){
this.onRecievingResults(this.loginUser)
this.router.navigateByUrl('/stats/list')
}
The service:
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
}
My other service:
ngOnInit(): void {
this.authService.dataEmitter.subscribe(data => console.log(data))
}
public currentUser:User | null = null
The problem is that in the component I want to use the User data after login the app I have "null", but in the method that I use in my service to update that data, I can get the User data. what I am doing wrong?
Solution
The subscription is asynchronous, so the next()
on your Subject will be called before this.currentUser
is updated.
So, you could just emit the Subject inside of the subscription.
public saveData(value:loginInterface){
this.loginUser(value).subscribe(() =>
this.dataUserSource.next(this.currentUser)
);
}
Also, it would be more clear if you moved the contents of the map()
function inside the subscription.
Answered By - Bastian Bräu
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.