【问题标题】:Failed to export .guard to another lib Angular无法将 .guard 导出到另一个库 Angular
【发布时间】:2021-05-20 06:36:41
【问题描述】:

我正在尝试将共享库中的 Router Guard 用于应用程序路由模块(在应用程序级别)。

我创建了这个 RouterGuard (route.guard.ts):

@Injectable({
  providedIn: 'root'
})

export class RouteGuard implements CanActivate {

  constructor(private router: Router) {}

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
    this.router.navigate(['login']);
    return false;
  }
}

在共享库上我试图导出这个类。

import {RouteGuard} from './auth/guard/route.guard';

@NgModule({
  imports: [CommonModule, MaterialModule, RouteGuard],
  exports: [MaterialModule, RouteGuard]
})
export class SharedModule {}

最后,我需要在应用程序级别使用这个守卫来检查我的路线。

const routes: Routes = [
  {
    path: '',
    component: LoggedComponent,
    children: [
      {path: '', component: HomeComponent}
    ],
    // Here
    canActivate: [RouteGuard]
  },
  {
    path: '',
    component: AuthComponent,
    children: [
      {path: '', redirectTo: 'login', pathMatch: 'full'},
      {path: 'login', component: LoginComponent},
      {path: 'signin', component: SigninComponent}
    ]
  }
];

但是我得到了这个错误:

error NG6002: Appears in the NgModule.imports of AppModule, but itself has errors

11 export class SharedModule {}

【问题讨论】:

    标签: angular angular-routing ng-modules angular-guards


    【解决方案1】:

    你只能将它导入到一个位置,你正在将它导入到 app-module 和 sharedmodule 中。这会导致您出现问题,请从 app-module 中删除防护导入,然后仅将其导入到共享模块中,然后将共享模块直接导入到 app 模块中。然后将你的守卫导入你的应用路由器模块。

    顺便说一句,我总是根据 observable 来制作路由器防护,但您的问题再次出现与导入多个模块有关。

     canActivate(
        next: ActivatedRouteSnapshot,
        state: RouterStateSnapshot): Observable<boolean> {
        
        this.router.navigate(['login']);
            return false;
        }
    

    【讨论】:

      猜你喜欢
      • 2018-07-21
      • 1970-01-01
      • 1970-01-01
      • 2021-03-02
      • 1970-01-01
      • 2019-04-26
      • 2019-07-23
      • 2021-03-27
      • 1970-01-01
      相关资源
      最近更新 更多