TypeError:guard不是函数

时间:2018-01-19 12:20:18

标签: angular typescript

我不知道是否让一些细节通过,或者我做错了什么,但我找不到导致错误的原因。我的目标是做一些不断检查用户是否在每次访问页面内的路径时都登录的内容。我使用Angular 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.intercpetor:

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

enter image description here

4 个答案:

答案 0 :(得分:16)

可能导致此问题的另一个问题是,如果您尝试将CanActivate保护用作另一种保护,例如CanActivateChild

答案 1 :(得分:5)

我更改了代码中的那部分并且它有效

import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router';

import { AuthService } from './auth.service';

@Injectable()
export class RoutesInterceptor implements CanActivate {

constructor(private auth: AuthService, private route: Router) {}

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
    if (this.auth.isUserAuthenticated()) {
        return true;
    }
    this.route.navigate(['./login']);
    return false;
  }
}

如果您尚未登录,我忘了重定向

答案 2 :(得分:2)

RoutesInterceptor用于AppRoutingModule,而不是AppModule。因此,您应该在RoutesInterceptor中将provider列为AppRoutingModule

答案 3 :(得分:0)

尝试在RoutesInterceptor

providers中添加PagesModule