Dear stackoverflow community,
i have the following issue. I try to use FirebaseAuthentication together with Angular7 and im trying to secure routes with guards so only logged in users can for example visit the /profile url.
My login (login.component.ts) looks like this. At first I import AngularFireAuth and use it for logging in with Google, Facebook or Email. In the ngOnInit method I am subscribing to the authState so I can redirect to user. This is all working fine.
In the next step I wanted to write an AuthGuard for the /profile url so only logged in users can visit their profile. The non logged in users should be redirected to /login first.
My AuthGuard (auth.guard.ts) looks like this and is using a class AuthService (auth.service.ts) internally. This AuthService is injected and offers a method isAuthenticated. If the user is authenticated he should be presented with his profile, otherwise the AuthGuard should return false and redirect him to login.
The AuthService looks like this and its method isAuthenticated should return true if the user is logged in and false otherwise.
If i don't add this dummy return true at the end of the function he will always redirect me back to /login also when I am logged in. He also tells me that the function has no return value
So I know that this subscription is not enough in the isAuthenticated method but I am curious what the best solution would look like to detect if the user is logged in.
If one of you has a best practice type of solution it would be very nice if he could show me. There are not very many proper tutorials out there.
In the meantime I will try to keep looking for a solution on google. I hope someone of you can help me with this problem. Thank you :)
best regards Jan
subscription cannot return value.
you can use map instead of subscribe.
return this.afAuth.authState.pipe(map((res) => {
if (res && res.uid)
return true;
return false;
});
also change the return value signature of isAuthenticated Method from boolean
to Observable<boolean>
or Observable<boolean> | boolean