所以,我们有一个相当大的应用程序,我们开始进行优化....其中一个优化是延迟加载一些部分....
所以我们有一些示例用法的演示页面,我们不想在任何地方使用DEV环境...
如此懒惰的加载那部分很容易......
在我们的app-routing模块中
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路线,所有工作都很好,并且演示路线会被懒散地加载......
现在,如果我添加这个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);
}
}
一旦我点击演示路线,我就会收到此错误:
错误错误:未捕获(在承诺中):错误: StaticInjectorError [DevOnlyGuard]:
StaticInjectorError [DevOnlyGuard]: NullInjectorError:没有DevOnlyGuard的提供者!错误:StaticInjectorError [DevOnlyGuard]:....
即使我将Guard添加到app.module中的提供者列表中 像
providers: [
...
DevOnlyGuard,
];
有什么想法吗?
答案 0 :(得分:4)
从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 {}