因此,我们有一个很大的应用程序,并且我们开始进行优化...。其中一项优化是延迟加载某些部件...。
因此,我们有演示页面,其中包含示例用法的全部负载,除了在DEV环境外,我们在任何地方都不需要...
所以懒惰地加载那部分很容易...
在我们的应用程序路由模块中,
const routes: Routes = [
...
{path: 'design', canActivate: ['DevOnlyGuard'], loadChildren: 'app/pages/demo/demo.module#DemoPagesModule'},
...
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
因此,如果没有canActivate route可以正常工作,并且演示路由会延迟加载...
现在,如果我在卫兵中添加此canActivate,则看起来像这样
import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, CanActivateChild } from '@angular/router';
import { environment } from 'environments/environment';
@Injectable()
export class DevOnlyGuard implements CanActivate, CanActivateChild {
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
return (environment.envName === 'dev');
}
canActivateChild(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
return this.canActivate(route, state);
}
}
按下演示路线后,我会收到此错误消息:
即使将Guard添加到我的app.module中的提供程序列表中
喜欢
providers: [
...
DevOnlyGuard,
];
有任何想法吗?
最佳答案
从canActivate: ['DevOnlyGuard']
删除单引号
下面是我们应该如何使用canActivate的方法:
方法1:
@Injectable()
class CanActivateTeam implements CanActivate {
constructor(private permissions: Permissions, private currentUser: UserToken) {}
canActivate(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): Observable<boolean>|Promise<boolean>|boolean {
return this.permissions.canActivate(this.currentUser, route.params.id);
}
}
@NgModule({
imports: [
RouterModule.forRoot([
{
path: 'team/:id',
component: TeamCmp,
canActivate: [CanActivateTeam]
}
])
],
providers: [CanActivateTeam, UserToken, Permissions]
})
class AppModule {}
方法2(单引号...):
@NgModule({
imports: [
RouterModule.forRoot([
{
path: 'team/:id',
component: TeamCmp,
canActivate: ['canActivateTeam']
}
])
],
providers: [
{
provide: 'canActivateTeam',
useValue: (route: ActivatedRouteSnapshot, state: RouterStateSnapshot) => true
}
]
})
class AppModule {}
关于Angular(5)-延迟加载和canActivate保护-StaticInjectorError,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47701019/