Auth Guard可能因某些原因而无法工作

问题描述 投票:2回答:1

当我在路线上添加带有canActivate的AuthGuard服务时,当我尝试去/profile并且它将我重定向到localhost:4200时,应用程序崩溃了,甚至没有/home并且给出了这个错误:

错误错误:“[object Object]”

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

它不起作用!

angular guard canactivate
1个回答
2
投票

有同样的问题,解决方案是在我的app.module.ts中将Auth Guard添加到我的提供者

© www.soinside.com 2019 - 2024. All rights reserved.