【发布时间】:2018-05-19 06:59:44
【问题描述】:
我正在使用角度 CanActivate Authguard 接口来保护我的组件。
@Injectable()
export class AuthGuard implements CanActivate{
constructor(private router: Router, private authService: AuthenticationService) {}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean | Observable<boolean> | Promise<boolean> {
this.authService.isLoggedIn.take(1).map((isLoggedIn : boolean) => {
if(!isLoggedIn){
this.router.navigate(['/login']);
return false;
}
return true;
})
this.router.navigate(['/login']);
return false;
}
}
我像这样将它添加到我的路由器配置中。
const appRoutes: Routes = [
{path : '',redirectTo : 'login',pathMatch : 'full'},
{ path: 'home', component: HomeComponent,canActivate : [AuthGuard] }
]
我还将它添加到提供者数组中。
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
providers: [AuthGuard,
ExpenseService,SellDetailService,AuthenticationService],
styleUrls: ['./app.component.css']
})
但是当我运行应用程序时,它会出现以下错误
StaticInjectorError(AppModule)[AuthGuard]:
StaticInjectorError(平台:核心)[AuthGuard]:NullInjectorError:否 AuthGuard 的提供者!
我认为我正确地实现了它,但它不起作用。我做错了什么???
【问题讨论】:
-
尝试将其添加到主模块的提供者
-
您需要将其添加到模块的
providers部分,在该部分中您使用了使用防护装置的路由配置 -
另一个问题(与错误无关)是
authService.isLoggedIn是异步的,因此它后面的行将立即执行。所以它总是会重定向到登录 -
它需要添加到你的模块的 providers 数组中,而不是你的组件中
-
我已经详细给出了一个答案,提供了您看到错误的原因以及作为解决方案可供您使用的选项 :) 如果您有任何与此问题相关的其他问题或有其他问题问!祝你好运,编码愉快!
标签: angular auth-guard