gpt4 book ai didi

Angular AuthGuard 不工作

转载 作者:太空狗 更新时间:2023-10-29 19:36:19 24 4
gpt4 key购买 nike

我正在使用 Angular CanActivate Authguard 接口(interface)来保护我的组件。

@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(Platform: core)[AuthGuard]: NullInjectorError: No provider for AuthGuard!

我认为我正确地实现了它,但它不起作用。我做错了什么???

最佳答案

你应该将你的守卫的名字添加到 providers 数组中的 app.module像这样

提供商:[AuthGuard]

关于 Angular AuthGuard 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50422679/

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