6

When I add AuthGuard service with canActivate on routes, the app crashes when I try to go to /profile and it redirect me to localhost:4200, not even /home and gives this error:

ERROR Error: "[object Object]"

enter image description here

My code :

app.routing.ts

import { NgModule } from '@angular/core';
import { Routes, RouterModule, CanActivate } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { ProfileComponent } from './profile/profile.component';
import { LoginComponent } from './login/login.component';

import { AuthGuardService as AuthGuard } from './auth-guard.service';

const routes: Routes = [
  {path:'', redirectTo:'/home', pathMatch:'full'},
 {path:'home',component: HomeComponent},
  {path:'login',component: LoginComponent},
  {path:'profile',component: ProfileComponent,canActivate: [AuthGuard]}
];

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

app.module.ts

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

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HomeComponent } from './home/home.component';
import { LoginComponent } from './login/login.component';
import { ProfileComponent } from './profile/profile.component';
import { TopbarComponent } from './topbar/topbar.component';

import { AuthGuardService as AuthGuard} from './auth-guard.service';
import { AuthService} from './auth.service';

@NgModule({
  declarations: [
    AppComponent,
    HomeComponent,
    LoginComponent,
    ProfileComponent,
    TopbarComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule
  ],
  providers: [AuthGuard, AuthService],
  bootstrap: [AppComponent]
})
export class AppModule { }

auth-guard.servce.ts

import { Injectable } from '@angular/core';
import { Router, CanActivate, ActivatedRouteSnapshot } from '@angular/router';
import { AuthService } from './auth.service';

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

  constructor(public auth: AuthService, public router: Router) { }

  canActivate():boolean{
          if (localStorage.getItem('currentUser')) {
              // logged in so return true
              return true;
          }

          // not logged in so redirect to login page
          this.router.navigate(['/login']);
          return false;
      }
}

It doesn't work!

R. Richards
  • 24,603
  • 10
  • 64
  • 64
Ed i
  • 61
  • 1
  • 1
  • 2
  • Try to wrap the false part in the canActivate in an else block. – abdullahkady Aug 24 '18 at 22:43
  • Is it definitely being caused by the AuthGuardService? If you comment out everything in canActivate, and simply return true, does it still error? – user184994 Aug 24 '18 at 22:48
  • @user184994 tried to comment everything and return true; but i still get the same Error in my console, thanks for trying to help – Ed i Aug 24 '18 at 22:57
  • Okay, so the issue seemingly isnt caused by that bit of code... And if you remove `canActivate: [AuthGuard]` from the route config, do you still get the error? – user184994 Aug 24 '18 at 22:59
  • @user184994 when i remove canActivate: [AuthGuard] from the route config, everything works fine without any error – Ed i Aug 24 '18 at 23:41
  • I'm not able to reproduce your error when I copy that code I'm afraid: https://stackblitz.com/edit/angular-tixhbd?file=src%2Fapp%2Fauth-guard.service.ts Can you fork that StackBlitz, and try to reproduce the error you're seeing? – user184994 Aug 25 '18 at 05:56
  • @user184994 im not able to reproduce error with stackbltiz, code works fine with stackblitz. – Ed i Aug 25 '18 at 15:05

2 Answers2

8

Had this same issue, solution was to add the Auth Guard to my providers in my app.module.ts

You should also make sure that this is the only file in which it is added to the providers.

import { AuthGuardService } from './auth-guard.service';

@NgModule({
  declarations: [
      // whatever your declarations are
  ],
  imports: [
      // Whatever your imports are
  ],
  providers: [
      AuthGuardService
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }
Shane
  • 659
  • 1
  • 9
  • 19
  • have u got any solution, please share – Santhosh Oct 17 '19 at 14:10
  • @Santhosh to my answer above, I added the AuthGuardService check the `providers` array of the module – Shane Oct 18 '19 at 14:49
  • I have more than one provider including authInterceptor. What is the solution for multiple providers beside authGuard – Golden Lion Sep 16 '20 at 20:20
  • @GoldenLion You can add as many classes annotated with @Injectable() as you like to the providers array of a module, but you must make sure that each class is only included in ONE providers array per app – Shane Sep 17 '20 at 11:39
  • if authguard is injectable why do I need to add it to the application provider array? – Golden Lion Sep 18 '20 at 20:53
  • 1
    @GoldenLion prior to Angular 6 you had to add an `@Injectable()` service to the providers array, in Angular 6 and above if you use `@Injectable({ providedIn: 'root' })` then you don't as this is basically declaring the same thing (root is an alias for AppModule in this case). All Injectable Services needed to be provided somewhere – Shane Sep 25 '20 at 11:15
  • thanks, that answers why there are differences in some of the tutorials about authguard – Golden Lion Sep 25 '20 at 12:01
0

I couldn't get it to work for me in app.module.ts. It has to be in app-routing.module.ts

In fact, it has to be in providers, in EVERY routing module that you want to use it in. ALSO, make sure to add ,canActivate:[AuthGuardName] to EACH line of the routes array, in every routing module you want to protect....