Error: Uncaught (in promise): TypeError: guard is not a function TypeError: guard is not a function on Angular

149 Views Asked by At

Hi everyone I'm struggling with this error on my webapp and I followed the suggestion on the old topic but I still have the error. Here is my code. When I try to go on dashboard I receive a blank page and the address doesn't route anywhere it stays on localhost:4200.

App Routing

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { HomeComponent } from './pages/home/home.component';
import { AboutComponent } from './pages/about/about.component';
import { ContactComponent } from './pages/contact/contact.component';
import { Page404Component } from './pages/page404/page404.component';
import { PhotographyComponent } from './pages/photography/photography.component';
import { PaintingComponent } from './pages/painting/painting.component';
import { SculptureComponent } from './pages/sculpture/sculpture.component';
import { InstallationComponent } from './pages/installation/installation.component';
import { WorkComponent } from './pages/work/work.component';
import { ArtistComponent } from './pages/artist/artist.component';
import { LoginComponent } from './pages/login/login.component';
import { RegisterComponent } from './pages/register/register.component';
import { DashboardComponent } from './pages/dashboard/dashboard.component';
import { AuthGuard } from './shared/guard/auth.guard';

const routes: Routes = [
  {
    path: '',
    redirectTo: '/home',
    pathMatch: 'full'
  },
  {
    path: 'home',
    component: HomeComponent
  },
  {
    path: 'about',
    component: AboutComponent
  },
  {
    path: 'contact',
    component: ContactComponent
  },
  {
    path: 'photography',
    component: PhotographyComponent
  },
  {
    path: 'painting',
    component: PaintingComponent
  },
  {
    path: 'sculpture',
    component: SculptureComponent
  },
  {
    path: 'installation',
    component: InstallationComponent
  },
  {
    path: 'work',
    component: WorkComponent
  },
  {
    path: 'artist',
    component: ArtistComponent
  },
  {
    path: 'login',
    component: LoginComponent
  },
  {
    path: 'register',
    component: RegisterComponent
  },
  {
    path: 'dashboard',
    component: DashboardComponent,
    canActivate:[AuthGuard],
  },
  {
    path: '**',
    component: Page404Component
  }

];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

AuthGuard

import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, RouterStateSnapshot,Router,UrlTree } from '@angular/router';
import { AuthService } from '../services/auth.service';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root',
})
export class AuthGuard {
  constructor(public authService: AuthService, public router: Router) {}

  CanActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Observable<boolean> | Promise<boolean> | UrlTree | boolean {
    if (!this.authService.isLoggedIn()) {
      this.router.navigate(['login']);

    }
    return true;
  }
}

Service

import { HttpClient } from '@angular/common/http';
import { Injectable, NgZone } from '@angular/core';
import {
  Auth,
  signInWithEmailAndPassword,
  createUserWithEmailAndPassword,
  sendEmailVerification,
  sendPasswordResetEmail,
  User,
} from '@angular/fire/auth';
import { Router } from '@angular/router';
import {
  Database,
  set,
  ref,
  update,
  getDatabase,
} from '@angular/fire/database';

import { environment } from 'src/environments/environment';
import { Artist } from 'src/app/classes/artist';
import { BehaviorSubject } from 'rxjs';

@Injectable({
  providedIn: 'root',
})
export class AuthService {

  userData: any; // Save logged in user data
  usersUrl: string = environment.firebase.databaseURL + '/users';
  isLogged = new BehaviorSubject<boolean>(false);

  constructor(
    public fsAuth: Auth, // Inject Firebase auth service
    public router: Router,
    public ngZone: NgZone, // NgZone service to remove outside scope warning
    public database: Database,
    private http: HttpClient
  ) {
    this.fsAuth.onAuthStateChanged((user) => {
      if (user) {
        this.userData = user;
        localStorage.setItem('user', JSON.stringify(this.userData));
      } else {
        localStorage.removeItem('user');
      }
      this.isLogged.next(!!user);
    });
  }

  // Sign in with email/password
  async SignIn(auth: Auth, email: string, password: string) {
    try {
      await signInWithEmailAndPassword(auth, email, password);
      this.router.navigate(['dashboard']);
    } catch (error) {
      console.log(error);
    }
  }

  // Sign up with email/password
  async SignUp(auth: Auth, artist: Artist) {
    try {
      const result = await createUserWithEmailAndPassword(auth, artist.email, artist.password);
      this.writeUserData(artist, result.user);
      this.router.navigate(['dashboard']);
    } catch (error) {
      (error);
    }
  }

  writeUserData(artist: Artist, user: User) {
    const db = getDatabase();
    set(ref(db, 'users/' + user.uid), {
      uid: user.uid,
      artistname: artist.artistname,
      artistsurname: artist.artistsurname,
      email: user.email,
      profile_picture: artist.photoURL,
      coverImg: artist.coverImg,
      baCourse: artist.baCourse,
      maCourse: artist.maCourse,
      intro: artist.intro,
    });
  }

  // Reset password
  async ForgotPassword(auth: Auth, passwordResetEmail: string) {
    try {
      await sendPasswordResetEmail(auth, passwordResetEmail);
    } catch (error) {
      console.log(error);
    }
  }

  // Sign out
  async SignOut() {
    await this.fsAuth.signOut();
    localStorage.removeItem('user');
    this.router.navigate(['home']);
  }

  // Returns true when user is logged in
  isLoggedIn(): boolean {
    return this.isLogged.getValue();
  }

  // Get logged in user data
  getUser(): Artist {
    return this.userData as Artist;
  }
}

I followed the suggestion on the old topic but I still have the error.

1

There are 1 best solutions below

2
Bhagyashree Sarkar On

You are not returning anything in if condition. You must return false like below :

AuthGuard

export class AuthGuard {
  constructor(public authService: AuthService, public router: Router) {}

  CanActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Observable<boolean> | Promise<boolean> | UrlTree | boolean {
    if (!this.authService.isLoggedIn()) {
      this.router.navigate(['login']);
      return false;
    }
    return true;
  }
}