i just start to learn js / angular / javascript. I want to make an app so i just followed a yt video for a integration of firebase login inside an angular app. This is the example.
I have the following code inside my auth.guard.ts – I dont know how to finish the isLoggedIn() method beside the line from where i get the value of localstorage. Thank you in advance for your help.
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class AuthGuard implements CanActivate {
constructor(
public router: Router
){ }
get isLoggedIn(): boolean {
const token = JSON.parse(localStorage.getItem('loginToken') || '{}');
return (token !== null) ? true : false;
}
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
if(this.isLoggedIn !== true) {
this.router.navigate(['home'])
}
return true;
}
}
2
Answers
Problem solved, thanks to @ye-olde-dev.
So in my app.module.ts i hade the firebase initialized like this:
What i changed is i put what olde-dev suggsted instead of what i had above wich is:
And in the Provides i had only AuthGuard but i needed to provide the firebase options aswell so my provider from app.module.ts is like this:
Thanks for help.
So, you actually don’t need to implement this yourself. The @angular/fire library already has it done for you.
You simply need to import from here:
and use in a route like so:
EDIT – forgot to include the declaration for the redirect
Note – this is as of @angular/fire 7.2.0.
If using a newer version the import location possible could have changed.
EDIT 2:
You’ll also need to provide the auth module in the appropriate ngModule. This is the import you’ll need:
then, in your imports section for the module add this import: