使用angular-cli构建角度5自定义模块包含预定义的路由阵列

问题描述 投票:0回答:2

我运行以下命令来创建具有单独路由文件的模块:

$ ng g module xyz --routing

此命令将创建这两个文件:

  • xyz.module.ts
  • XYZ-routing.module.ts

在文件xyz-routing.module.ts中有一个空的路由数组

const routes: Routes = [];

无论如何都要自动填充数组,例如使用预定义的模板,数组等?

angular angular-cli angular5 angular-routing
2个回答
0
投票

可以使用此链接了解angular schematics并使用它创建组件,服务和模块。

Schematics Collections是一组命名的原理图,由用户发布和安装。例如,Angular团队发布并维护官方@ schematics / angular集合,其中包含组件,模块和应用程序等原理图。


0
投票

如Debora在评论中分享的链接中所述,我运行了以下命令:

npm install -g @angular-devkit/schematics-cli

schematics blank --name=crud-module

cd crud-module
npm install

然后我将crud-module/package.json中的包名改为crud-module

我改变了文件crud-module/src/collection.json

{
  "$schema": "../node_modules/@angular-devkit/schematics/collection-schema.json",
  "schematics": {
    "crud-module": {
      "description": "A blank schematic.",
      "factory": "./crud-module/index#crudModule"
    }
  }
}

剩下的部分是修改文件,crud-module/src/crud-module/index.ts

import { Rule, SchematicContext, Tree } from '@angular-devkit/schematics';


// You don't have to export the function as default. You can also have more than one rule factory
// per file.
export function crudModule(options: any): Rule {
  return (tree: Tree, _context: SchematicContext) => {
    var ucFirstName = options.name.substr(0,1).toUpperCase() + options.name.substr(1);
    console.log("ucFirstName", ucFirstName);
    tree.create(`src/app/components/`+options.name+`/`+options.name+'.module.ts', `import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterModule } from '@angular/router';
import { `+ucFirstName+`Service } from './`+options.name+`.service';

@NgModule({
  imports: [
    RouterModule.forChild([
        {
          component: List`+ucFirstName+`Component,
          path: '',
        },
        {
          component: Add`+ucFirstName+`Component,
          path: 'add',
        },
        {
            component: Edit`+ucFirstName+`Component,
            path: 'edit/:id',
        },
    ]),
    CommonModule,
  ],
  declarations: [],
  providers: []
})
export class `+ucFirstName+`Module { }`);
    return tree;
  };
}

然后我替换了这个命令:

ng g module MODULE_NAME

使用此命令:

schematics  ./crud-module:crud-module --name=MODULE_NAME --dry-run=false

我的自定义模块创建:)

© www.soinside.com 2019 - 2024. All rights reserved.