-1

Before implementing authGuard in my project, everything was working fine. But, it seems authguard throwing an error.

I removed the authguard from the page and it was working. but then again added it back gave error.

App.routing.module.ts

  { path: 'login', loadChildren: './Users/login/login.module#LoginPageModule' },
  { path: 'students/:uName', loadChildren: './Academic/Students/students/students.module#StudentsPageModule',canActivate: [AuthGuard],},
  { path: 'registerclass', loadChildren: './Academic/Students/registerclass/registerclass.module#RegisterclassPageModule',canActivate: [AuthGuard], },
  { path: 'schedule', loadChildren: './Academic/Students/schedule/schedule.module#SchedulePageModule',canActivate: [AuthGuard], },
  { path: 'faculties', loadChildren: './Academic/Faculty/faculties/faculties.module#FacultiesPageModule',canActivate: [AuthGuard], },
  { path: 'addclass', loadChildren: './Academic/Faculty/addclass/addclass.module#AddclassPageModule',canActivate: [AuthGuard], },

auth.guard.ts

import { Injectable } from '@angular/core';
import { CanActivate,ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree,Router } from '@angular/router';
import { Observable } from 'rxjs';
import * as firebase from 'firebase/app'
import 'firebase/auth'


@Injectable({
  providedIn: 'root'
})
export class AuthGuard implements CanActivate {


  constructor(private router: Router) {}

  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): boolean | Observable<boolean> | Promise<boolean> {
    return new Promise((resolve, reject) => {
      firebase.auth().onAuthStateChanged((user: firebase.User) => {
        if (user) {
          resolve(true);
        } else {
          console.log('User is not logged in');
          this.router.navigate(['/login']);
          resolve(false);
        }
      });
    });
  }


}// close of class Authguard

app.module.ts

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouteReuseStrategy } from '@angular/router';

import { IonicModule, IonicRouteStrategy } from '@ionic/angular';
import { SplashScreen } from '@ionic-native/splash-screen/ngx';
import { StatusBar } from '@ionic-native/status-bar/ngx';

import { AppComponent } from './app.component';
import { AppRoutingModule } from './app-routing.module';

import { AngularFireModule } from '@angular/fire'; //To initialize firebaseconfig
import { AngularFireAuthModule } from '@angular/fire/auth';
import { AngularFirestoreModule } from '@angular/fire/firestore';

var firebaseConfig = {
  apiKey: "AIzaSyC7f8sjVR-cSeeee3ZbEErwOQReowwpTL0",
  authDomain: "msuproject-74e5a.firebaseapp.com",
  databaseURL: "https://msuproject-74e5a.firebaseio.com",
  projectId: "msuproject-74e5a",
  storageBucket: "msuproject-74e5a.appspot.com",
  messagingSenderId: "748587348290",
  appId: "1:748587348290:web:e10fe4336779cd2ee158db",
  measurementId: "G-GE58MG9QF6"
};
@NgModule({
  declarations: [AppComponent],
  entryComponents: [],
  imports: [
    BrowserModule,
    IonicModule.forRoot(),
    AppRoutingModule,
    AngularFireModule.initializeApp(firebaseConfig),
    AngularFireAuthModule,
    AngularFirestoreModule
  ],
  providers: [
    StatusBar,
    SplashScreen,
    { provide: RouteReuseStrategy, useClass: IonicRouteStrategy }
  ],
  bootstrap: [AppComponent]
})
export class AppModule {}

home.html

<ion-card style="text-align: center; background-color: rgb(19, 4, 4);">
        <nav class="navCard">
            <h1 class="h1Card">
                <a [routerLink]="['/login']">Login</a> |
                <a [routerLink]="['/faculties']">Faculty</a> |
                <a href="https://lib.murraystate.edu/">Library</a> |
                <a href="#">Info</a> 
            </h1>
          </nav>
        </ion-card>

So, when I click on "Faculty", It should take me to Faculty page rather than crashing the page.

Mr.Shah
  • 61
  • 7
  • Why not use the methods provided to you via @angular/fire? – Phix Nov 09 '19 at 22:34
  • Can you explain a little bit more? – Mr.Shah Nov 09 '19 at 23:03
  • You have that package installed, but you're using the "vanilla" firebase methods in your guard. Not sure why it's crashing at a glance but I don't see a reason not to use the services available to you. – Phix Nov 09 '19 at 23:08
  • Sorry for late response but how do you know its either vanilla or something else? i am using but dont have enough knowledge. it would be great if you provide some reference – Mr.Shah Nov 28 '19 at 20:37
  • You're importing `firebase/auth` instead of `@angular/fire/auth` which does the heavy lifting for you. Not sure when it was added to the package, but there's a section in the docs with [dedicated auth guards](https://github.com/angular/angularfire/blob/master/docs/auth/router-guards.md). – Phix Nov 28 '19 at 21:06

2 Answers2

0

First move the firebaseconfig object to another ts file, then inside the auth.guard.ts do the following:

import * as config from './config.ts';

let firebaseInit = firebase.initializeApp(config.firebaseConfig);
Peter Haddad
  • 78,874
  • 25
  • 140
  • 134
0

The other solution uses the firebase javascript SDK but since you are importing AngularFire you may as well use that.

auth.guard.ts

 constructor(private router: Router,
                private afAuth: AngularFireAuth,
                private ngZone: NgZone) { }

 canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): boolean | Observable<boolean> | Promise<boolean> {
    return new Promise((resolve, reject) => {
      this.afAuth.auth.onAuthStateChanged((user: firebase.User) => this.ngZone.run(() => {
        if (user) {
          resolve(true);
        } else {
          console.log('User is not logged in');
          this.router.navigate(['/login']);
          resolve(false);
        }
      });
    });
  }

Also I recommend moving your firebaseConfig into the environment file so you can have different ones for dev and production.

app.module.ts

import { environment } from '../environments/environment';

...
    imports: [
...
AngularFireModule.initializeApp(environment.firebaseConfig),
...
MadMac
  • 4,048
  • 6
  • 32
  • 69