我不知道我是否漏掉了一些细节,或者我做错了什么,但我找不到是什么导致了这个错误。我的目标是做一些事情,在用户每次访问页面内的路由时,都会检查用户是否已登录。我用角度5。
App.module:
import { BrowserModule } from '@angular/platform-browser';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { LoginComponent } from './pages/autenticacao/login.component';
import { AuthService } from './auth/auth.service';
import { RoutesInterceptor } from './auth/routes.interceptor';
import * as $ from 'jquery';
@NgModule({
declarations: [ AppComponent, LoginComponent ],
imports: [
BrowserModule,
BrowserAnimationsModule,
AppRoutingModule,
],
bootstrap: [AppComponent],
providers: [ AuthService, RoutesInterceptor, ],
})
export class AppModule {
}
routes.interpetor:路径.interpetor:
import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { AuthService } from './auth.service';
@Injectable()
export class RoutesInterceptor implements CanActivate {
constructor(private auth: AuthService) {}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
return this.auth.isUserAuthenticated();
}
}
我的路线:
import { NgModule } from '@angular/core';
import { ExtraOptions, RouterModule, Routes } from '@angular/router';
import { LoginComponent } from './pages/autenticacao/login.component';
import { RoutesInterceptor } from './auth/routes.interceptor';
const routes: Routes = [
{ path: 'pages', loadChildren: 'app/pages/pages.module#PagesModule', canActivate: [RoutesInterceptor] },
{ path: 'login', component: LoginComponent },
{ path: '', redirectTo: 'pages', pathMatch: 'full' },
{ path: '**', redirectTo: 'pages' },
];
const config: ExtraOptions = {
useHash: true,
};
@NgModule({
imports: [RouterModule.forRoot(routes, config)],
exports: [RouterModule],
})
export class AppRoutingModule {
}
最佳答案
另一个可能导致这种情况的问题是,如果您尝试将CanActivate
保护用作另一种类型的保护,比如CanActivateChild