gpt4 book ai didi

angular - 错误 : Uncaught (in promise): TypeError: guard is not a function

转载 作者:太空狗 更新时间:2023-10-29 17:21:44 25 4
gpt4 key购买 nike

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

//Authgaurd代码

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

最佳答案

You must have to implement both the CanActivate and CanAcitvateChild interface on the AuthGuard in order to use it on canActivateChild

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

关于angular - 错误 : Uncaught (in promise): TypeError: guard is not a function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48447774/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com