3

我有一个角度应用程序,其app.component.html如下所示:

<div>
    <app-nav-bar></app-nav-bar>
</div>
<div>
 <router-outlet></router-outlet>
</div>

' 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]}

我使用 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']);
    }
    
     }));
  

   }

 }

我没有在 app.modules.ts 的任何声明或条目组件中添加“AuthguardGuard”,现在我遇到了如下几个问题。

  1. nav-bar.component.ts先加载,然后 auth-guard 如下:但我希望 auth-guard 先授权并加载 app-component.html,

    导航栏被加载 // 从 app-nav-bar.ts 打印的控制台在 auth-guard 中成功 // 从 auth-guard.guard.ts 打印的控制台

  2. 以下错误来自 angular-auth-guard

    ERROR 错误:未捕获(承诺中):错误:未找到 e 的组件工厂。你把它添加到@NgModule.entryComponents 了吗?错误:找不到 e 的组件工厂。你把它添加到@NgModule.entryComponents 了吗?

4

0 回答 0