如何制作在Angular 7中输入的Route数据?

dis*_*ame 9 javascript typescript angular angular-aot

import { environment } from '@env/environment';

export const routes: Routes = [
  {
    path: '',
    children: [
      {
        path: 'organisations',
        component: OrganisationListComponent,
        data: {
          [environment.router.data.resourceName]: 'ORGANISATION' // <- error
        }
      },
      {
        path: 'organisations/create',
        component: OrganisationCreateComponent,
        data: {
          [environment.router.data.resourceName]: 'ORGANISATION_LIST' // <- error
        },...
      }

Run Code Online (Sandbox Code Playgroud)

这是我的路由模块文件之一的一部分。如您所见,我希望路由数据具有我在环境文件中定义的名称的属性。但这在使用--aot标志进行编译时将无法正常工作。这是错误:

ERROR in Error during template compile of 'AdminRoutingModule'
  Expression form not supported in 'routes'
    'routes' contains the error at app/admin/admin-routing.module.ts(30,11).
Run Code Online (Sandbox Code Playgroud)

我的应用程序中大约有30条路由,并且所有路由都具有带有键“ resourceName”的data属性。而且我不想在我的应用程序中重复此字符串30次。

我不能创建具有resourceName属性的类并在数据中实例化它,因为在路由配置中也不允许使用函数表达式。

有没有解决的办法,还是使用AOT编译器根本无法实现?

编辑:这是environement.ts文件:

export const environment = {
  production: true,
  version: '1.0.0',
  router: {
    data: {
      resourceName: 'resourceName'
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

And*_*ang 3

声明您自己的Route数据类型。从@angular/router's扩展Route,因此都是类型安全的。这样,就可以断言该resourceName属性的存在,否则甚至可以忽略该属性。

该过程中不需要涉及环境模块。

import { RouterModule, Route } from '@angular/router';

export interface MyRoute extends Route {
    data: {
        resourceName: string;
    };
}

export declare type MyRoutes = MyRoute[];

export const routes: MyRoutes = [
  {
    path: '',
    children: [
      {
        path: 'organisations',
        component: OrganisationListComponent,
        data: {
          resourceName: 'ORGANISATION'
        }
      },
      {
        path: 'organisations/create',
        component: OrganisationCreateComponent,
        data: {
          resourceName: 'ORGANISATION_LIST'
        },...
      }


Run Code Online (Sandbox Code Playgroud)