Lis*_*isa 5 typescript canactivate auth-guard angular8
我有一个有角度的应用程序,其app.component.html如下所示:
<div>
<app-nav-bar></app-nav-bar>
</div>
<div>
<router-outlet></router-outlet>
</div>
Run Code Online (Sandbox Code Playgroud)
' app-nav-bar ' 是一个在启动此 Angular 应用程序时加载的组件,其 nav-bar.component.ts 具有 ' ngAfterViewInit ' 以及一些控制台消息,如下所示:
ngAfterViewInit() { console.log("导航栏已加载") ; }
我有一个路由模块(app-routing.module.ts),它定义路由如下:
const routes: Routes = [
{path:'accessdenied',component:AccessDenied },
{ path: 'region', loadChildren:'//pathToSharedModule#RegionSharedModule',canActivate:[AuthguardGuard]},
{path:'names',loadChildren:'Path'},
{path: '**',component:RegionSharedModule ,canActivate:[AuthguardGuard]}
Run Code Online (Sandbox Code Playgroud)
我使用 Angular Guard 服务根据 API 对用户进行授权并激活相应的路由。 authguard.guard.ts
import { Injectable } from '@angular/core';
//some other basic modules got imported
@Injectable({
providedIn: 'root'
})
export class AuthguardGuard implements CanActivate {
constructor(private router:Router,private shared:SharedServiceContainer,private api:ApiService){}
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
return this.api.getDataFrmAPi(//sever-api).pipe(map(res =>{
if(res["status"] == "success"){
console.log("success in auth-guard");
let perms = res["data"]
this.shared.permissions = perms; //am assigning values to a shared service variable
if(perms.read_write){ //if user has read_write permission allow access to page
//console throws an error No component factory found
return true;
}
else if(perms.read_only){ //if user has read_only , navigate to 'names' route
this.router.navigate(['/names']);
return false;
}
else{ //else redirect to a component that shows 'access denied' msg
this.router.navigate(['/accessdenied']);
return false;
}
}
else{
this.router.navigate(['/accessdenied']);
}
}));
}
}
Run Code Online (Sandbox Code Playgroud)
我没有在 app.modules.ts 的任何声明或入口组件中添加“AuthguardGuard”,现在我遇到了如下几个问题。
首先加载nav-bar.component.ts,然后加载 auth-guard ,如下所示:但我期望 auth-guard 首先授权并加载 app-component.html,
导航栏已加载 //从 app-nav-bar.ts 打印的控制台 auth-guard 成功 //从 auth-guard.guard.ts 打印的控制台
下面的错误来自 angular-auth-guard
错误错误:未捕获(承诺):错误:找不到 e 的组件工厂。您是否将其添加到@NgModule.entryComponents?错误:找不到 e 的组件工厂。您是否将其添加到@NgModule.entryComponents?