Reputation: 9
What I am trying to accomplish is to see if a user session is already there and if so log them in. But I am having issues with how to execute this properly. It's most likely to do with code execution order, but I do not understand what to do to solve this. Perhaps async?
Getting:
TypeError: Cannot read property 'subscribe' of undefined
Sidebar.component.ts:
ngOnInit(): void {
this.authService.isLoggedIn.subscribe(res => {
if (res){
this.isLoggedIn = true;
} else {
this.isLoggedIn = false;
}
});
}
auth.service.ts:
get isLoggedIn(): Observable<boolean> {
const authToken = this.cookieService.get('cookiehere');
// console.log(authToken);
if (authToken) {
this.getUserBySession(authToken).subscribe(res => {
console.log(res);
return of(true);
}, error => {
return of(false);
});
}
if (!authToken){
console.log('No token found!');
return of(false);
}
}
getUserBySession(session) {
return this.http.get(`${this.apiPrefix}/auth/get_user_by_session?session=${session}`, { headers: this.headers })
.pipe(map((res: any) => {
if (res.user) {
this.currentUser = res.user;
return res;
} else {
return res;
}}));
}
Upvotes: 0
Views: 817
Reputation: 1479
You're subscribing to an observable here but you're not returning an observable from the getter. The return of(true)
you have there returns from inside the subscribe
callback, not the getter. You would have to change it to return the original observable from the getUserBySession
function
get isLoggedIn(): Observable<boolean> {
const authToken = this.cookieService.get('vmkr');
if (authToken) {
return this.getUserBySession(authToken).pipe(
map(() => true),
catchError(() => of(false))
);
} else {
console.log('No token found!');
return of(false);
}
}
Though I imagine a getter here could cause problems with multiple subscriptions somewhere down the line.
Upvotes: 3