Angular Inject() 函数不提供到 CanActivateFn 的路由器

mhl*_*hld 4 angular-routing angular angular-router

我正在尝试使用 Angular v14 功能之一,即 CanActivateFn。

不幸的是,当我的守卫被执行并且返回的语句为假时,我没有被重定向。正在抛出错误:

未捕获(承诺中): TypeError:router.parseUrl 不是函数 TypeError:router.parseUrl 不是函数

允许实体.guard.fn.ts

export function AllowedEntitiesGuard(allowedEntities: string[]): CanActivateFn {
  const router = Inject(Router);
  return (route: ActivatedRouteSnapshot) => {
    const entitiesTypeParameter = route.paramMap.get('entitiesType')

    return allowedEntities.indexOf(entitiesTypeParameter) !== -1 ? true : router.parseUrl('/');
  };
}
Run Code Online (Sandbox Code Playgroud)

主要.ts

bootstrapApplication(AppComponent, {
  providers: [
    provideHttpClient(withInterceptorsFromDi()),
    {
      provide: HTTP_INTERCEPTORS,
      useClass: JwtInterceptor,
      multi: true,
    },
    { provide: APP_CONFIG, useValue: environment },
    provideRouter(APP_ROUTES),
  ],
});
Run Code Online (Sandbox Code Playgroud)

当我尝试 console.log 路由器时,它向我显示其函数 ParamDecorator 实例。我做错了什么?

mhl*_*hld 6

该问题与错误导入有关。

我应该使用注入而不是注入。

允许实体.guard.fn.ts

// Good!
import { inject } from '@angular/core';

// Absolutely wrong!    
import { Inject } from '@angular/core';
Run Code Online (Sandbox Code Playgroud)

另一件事。由于NG0203 ,我无法像上面在原始帖子中那样使用inject() 。我必须将 Router 注入移至 CanActivateFn 主体中,因此它属于上下文。

我最终得到的守卫看起来像这样:

允许实体.guard.fn.ts

export function AllowedEntitiesGuard(allowedEntities: string[]): CanActivateFn {
  return (route: ActivatedRouteSnapshot): boolean | UrlTree => {
    const router: Router = inject(Router);
    const entitiesType: string | null = route.paramMap.get(
      'entitiesType'
    );

    return allowedEntities.indexOf(entitiesType) !== -1 ? true : router.parseUrl('/');
  };
}
Run Code Online (Sandbox Code Playgroud)

通过这种方法,我可以将实体直接传递给守卫。无需指定额外的数据参数,然后从ActivatedRouteSnapshot 中检索它。

应用程序.routes.ts

canActivate: [AllowedEntitiesGuard(['EntityTypeOne', 'EntityTypeTwo'])
Run Code Online (Sandbox Code Playgroud)