错误:未捕获(在承诺中):TypeError:guard不是函数

时间:2018-01-25 16:33:52

标签: angular typescript angular4-router canactivate

我正在Angular 4中编写一个Authguard,以防止在没有登录的情况下访问路由。但是,我收到了这个错误。以下是Authgaurd和Routing in App模块中的代码。请帮助解决问题。

// Authgaurd Code

import { ActivatedRouteSnapshot, CanActivate, Route, Router, 
RouterStateSnapshot } from '@angular/router';
import { Store } from '';
import { Observable } from 'rxjs/Observable';
import { map, take } from 'rxjs/operators';
import { Observer } from 'rxjs';
import { Globals } from '../../app.global';
import { CRMStorageService } from '../services/storage.service';
import 'rxjs/add/operator/take';

@Injectable()
export class AuthGuard implements CanActivate {

constructor(private router: Router,private storageService: StorageService) { 
 }

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): 
Observable<boolean> {
return this.storageService.getItem(Globals._CURRENT_USER_KEY).take(1).map 
(token => {
    if (token) {
        return true;
    } else {
        this.router.navigate(['/login']);
    }
  });
}
}

//在App模块中路由

const appRoutes: Routes = [
{ path:'',redirectTo:'/login', pathMatch: 'full' },
{ path:'login', component: LoginComponent },
{ path:'reset/:token', component: ResetpasswordComponent },
{
path: '',
canActivateChild: [AuthGuard],
children: [
{ path:'dashboard', component: DashboardComponent },
{ path:'customerlist', component: CustomerlistComponent }
]
},
{ path: '**', component: ErrorComponent }
];

@NgModule({
imports: [
        RouterModule.forRoot(appRoutes,
        {
         enableTracing: false // <-- debugging purposes only
        })],
 declarations: [
  AppComponent,
 .
 .
],
providers: [AuthGuard],
exports: [],
bootstrap: [AppComponent]})

export class AppModule { }

2 个答案:

答案 0 :(得分:13)

  

您必须在AuthGuard上实施 CanActivate CanAcitvateChild 界面才能在canActivateChild上使用

export class AuthGuard implements CanActivate, CanActivateChild {
  ...
  canActivateChild(route: ActivatedRouteSnapshot, state: RouterStateSnapshot):  boolean {
      return this.canActivate(route, state);
 }
}

答案 1 :(得分:8)

  

只需将 canActivateChild 替换为路由处理程序中的 canActivate 即可使用

const appRoutes: Routes = [
    { path: '', redirectTo: '/login', pathMatch: 'full' },
    { path: 'login', component: LoginComponent },
    { path: 'reset/:token', component: ResetpasswordComponent },
    {
        path: '',
        canActivate: [AuthGuard],
        children: [
            { path: 'dashboard', component: DashboardComponent },
            { path: 'customerlist', component: CustomerlistComponent }
        ]
    },
    { path: '**', component: ErrorComponent }
];

@NgModule({
    imports: [
        RouterModule.forRoot(appRoutes,
            {
                enableTracing: false // <-- debugging purposes only
            })],
    declarations: [
        AppComponent,
    .
    .
    ],
    providers: [AuthGuard],
    exports: [],
    bootstrap: [AppComponent]
})

export class AppModule { }