skip to Main Content

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


  1. Chosen as BEST ANSWER

    Problem solved, thanks to @ye-olde-dev.

    So in my app.module.ts i hade the firebase initialized like this:

    AngularFireModule.initializeApp(environment.firebase) 
    

    What i changed is i put what olde-dev suggsted instead of what i had above wich is:

    provideFirebaseApp(() => initializeApp(environment.firebase))
    

    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:

    providers: [AuthGuard, { provide: FIREBASE_OPTIONS, useValue: environment.firebase }], 
    

    Thanks for help.


  2. 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:

    import {AuthGuard, redirectUnauthorizedTo} from '@angular/fire/auth-guard';
    

    and use in a route like so:

    EDIT – forgot to include the declaration for the redirect

    const redirectUnauthorizedToLogin = () => redirectUnauthorizedTo(['your login page here']);
    
    {
       path: 'admin',
       component: AdminComponent,
       canActivate: [AuthGuard],
       data: {authGuardPipe: redirectUnauthorizedToLogin}
    }
    

    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:

    import { getAuth, provideAuth } from '@angular/fire/auth';
    

    then, in your imports section for the module add this import:

    provideAuth(() => getAuth()),
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search