Auth Guard可以出于某种原因无法激活

时间:2018-08-24 22:18:02

标签: angular guard canactivate

当我在路由上添加canActivate的AuthGuard服务时,当我尝试转到/profile时,应用崩溃,它将我重定向到localhost:4200,甚至没有重定向到/home,并且出现此错误:

  

错误错误:“ [对象对象]”

enter image description here

我的代码:

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;
      }
}

它不起作用!

1 个答案:

答案 0 :(得分:2)

遇到同样的问题,解决方法是将Auth Guard添加到我的app.module.ts中的提供商中。