Home>Article>Web Front-end> Angular + NG-ZORRO quickly develop a backend system
This article will share with you aAngularpractical experience to learn how to quickly develop a backend system using angualr combined with ng-zorro. I hope it will be helpful to everyone!
We have learned a lot aboutangular
in the past few days. This time we have a small finished product.
angualr
Combined withng-zorro
to develop a backend system quickly and standardizedly. [Related tutorial recommendations: "angular tutorial"]
System functions include the following:
All services use simulated data.
Let’s do it as we are told.
Combined with ng-zorro
##angularThe more popular
uiframeworks are:
Ant DesignI believe people who do front-end development are familiar with it. So here we combine it with the
NG-ZORROframework. If you are familiar with
Vueor
Reactversion of
Ant Design, I believe you can connect seamlessly~
angular-clito generate a project
ng-zorro.
ng-zorrois very simple: enter the
ng-zorroroot directory and execute
ng add ng-zorro-antdThat is Can.
Of course you can also executeCombinednpm install ng-zorro-antd
to add, but it is not recommended.
ng-zorroAfter completion, we run the project
npm run start, you will be in
http://localhost:4200page, see the content below.
Not Bad, Bro.
Configure routing
We changed it tohashrouting and added user routing. The scaffolding has done it for us, we only need to make some minor modifications.
userUser's list page, use
ng-zorroin
tableComponent
formcomponent## in
ng-zorro
component inng-zorro
component as needed
introduces:
Simple and easy to understand principle, we do not use// app.module.ts import { ReactiveFormsModule } from '@angular/forms'; import { NzTableModule } from 'ng-zorro-antd/table'; import { NzModalModule } from 'ng-zorro-antd/modal'; import { NzButtonModule } from 'ng-zorro-antd/button'; import { NzFormModule } from 'ng-zorro-antd/form'; import { NzInputModule } from 'ng-zorro-antd/input'; // ... imports: [ // 是在 imports 中添加,而不是 declarations 中声明 NzTableModule, NzModalModule, NzButtonModule, NzFormModule, ReactiveFormsModule, NzInputModule ],
here for nesting of routes:// app.routing.module.ts import { NgModule } from '@angular/core'; import { Routes, RouterModule, PreloadAllModules } from '@angular/router'; import { WelcomeComponent } from './pages/welcome/welcome.component'; import { UserComponent } from './pages/user/user.component'; import { UserInfoComponent } from './pages/user/user-info/user-info.component'; // 相关的路由 const routes: Routes = [ { path: '', pathMatch: 'full', redirectTo: '/welcome' }, { path: 'welcome', component: WelcomeComponent }, { path: 'user', component: UserComponent }, { path: 'user/add', component: UserInfoComponent }, { path: 'user/edit/:uuid', component: UserInfoComponent } ]; @NgModule({ imports: [RouterModule.forRoot( routes, { useHash: true,// 使用 hash 模式 preloadingStrategy: PreloadAllModules } )], exports: [RouterModule] }) export class AppRoutingModule { }
Change the menuThe menu generated using scaffolding does not match the functions we need to develop, let’s adjust it.
// app.component.htmlMenu display, if we need to do permission management, we need the backend to cooperate with the value transfer, and then we will render the relevant permission menu to the page
After replacing the above code, the basic skeleton obtained is as follows:
Complete user listNext, complete the skeleton of the user list. Because we use the
UIframework, it is extremely convenient for us to write:
// user.component.htmlWe simulated some data in the assetsName Position Action {{data.name}} {{data.position}} Delete
folderuser.json
:
After writing the service, we called to get the user's data:{ "users": [ { "uuid": 1, "name": "Jimmy", "position": "Frontend" }, { "uuid": 2, "name": "Jim", "position": "Backend" } ], "environment": "development" }
// user.component.ts import { Component, OnInit } from '@angular/core'; import { UserService } from 'src/app/services/user.service'; @Component({ selector: 'app-user', templateUrl: './user.component.html', styleUrls: ['./user.component.scss'] }) export class UserComponent implements OnInit { public list: any = [] constructor( private readonly userService: UserService ) { } ngOnInit(): void { if(localStorage.getItem('users')) { let obj = localStorage.getItem('users') || '{}' this.list = JSON.parse(obj) } else { this.getList() } } // 获取用户列表 getList() { this.userService.getUserList().subscribe({ next: (data: any) => { localStorage.setItem('users', JSON.stringify(data.users)) this.list = data.users }, error: (error: any) => { console.log(error) } }) } }
Because no back-end service is introduced, here we use
localstorageto record the status.After completing the above, we get the list information as follows:
us Simply create a form, which contains only two fields, namely
nameandposition
. These two functions share a common form~We add in
:
The page looks like this:// user-info.component.html <form nz-form [formGroup]="validateForm" class="login-form" (ngSubmit)="submitForm()"> <nz-form-item> <nz-form-control nzErrorTip="请输入用户名!"> <input type="text" nz-input formControlName="username" placeholder="请输入用户名" style="width: 160px;" /> </nz-form-control> </nz-form-item> <nz-form-item> <nz-form-control nzErrorTip="请输入职位!"> <input type="text" nz-input formControlName="position" placeholder="请输入职位" style="width: 160px;"/> </nz-form-control> </nz-form-item> <button nz-button class="login-form-button login-form-margin" [nzType]="'primary'">确认</button> </form>
然后就是逻辑的判断,进行添加或者是修改。如果是连接带上uuid
的标识,就表示是编辑,show you the codes
。
// user-info.component.ts import { Component, OnInit } from '@angular/core'; import { FormBuilder, FormGroup, Validators } from '@angular/forms'; import { ActivatedRoute, ParamMap } from '@angular/router'; @Component({ selector: 'app-user-info', templateUrl: './user-info.component.html', styleUrls: ['./user-info.component.scss'] }) export class UserInfoComponent implements OnInit { public isAdd: boolean = true; public userInfo: any = [] public uuid: number = 0; validateForm!: FormGroup; constructor( private fb: FormBuilder, private route: ActivatedRoute, ) { } ngOnInit(): void { this.userInfo = JSON.parse(localStorage.getItem('users') || '[]') this.route.paramMap.subscribe((params: ParamMap)=>{ this.uuid = parseInt(params.get('uuid') || '0') }) // 是编辑状态,设置标志符 if(this.uuid) { this.isAdd = false } if(this.isAdd) { this.validateForm = this.fb.group({ username: [null, [Validators.required]], position: [null, [Validators.required]] }); } else { let current = (this.userInfo.filter((item: any) => item.uuid === this.uuid))[0] || {} // 信息回填 this.validateForm = this.fb.group({ username: [current.name, [Validators.required]], position: [current.position, [Validators.required]] }) } } submitForm() { // 如果不符合提交,则报错 if(!this.validateForm.valid) { Object.values(this.validateForm.controls).forEach((control: any) => { if(control?.invalid) { control?.markAsDirty(); control?.updateValueAndValidity({ onlySelf: true }); } }) return } // 获取到表单的数据 const data = this.validateForm.value // 新增用户 if(this.isAdd) { let lastOne = (this.userInfo.length > 0 ? this.userInfo[this.userInfo.length-1] : {}); this.userInfo.push({ uuid: (lastOne.uuid ? (lastOne.uuid + 1) : 1), name: data.username, position: data.position }) localStorage.setItem('users', JSON.stringify(this.userInfo)) } else { // 编辑用户,更新信息 let mapList = this.userInfo.map((item: any) => { if(item.uuid === this.uuid) { return { uuid: this.uuid, name: data.username, position: data.position } } return item }) localStorage.setItem('users', JSON.stringify(mapList)) } } }
我们先设定一个标志符isAdd
,默认是新建用户;当uuid
存在的时候,将其设置为false
值,表示是编辑的状态,对内容进行表单的回填。提交表单的操作也是按照该标志符进行判断。我们直接对localStorage
的信息进行变更,以保证同步列表信息。
删除功能
我们引入模态对话框进行询问是否删除。
// user.component.ts // 删除 delete(data: any) { this.modal.confirm({ nzTitle: '你想删除该用户?', nzOnOk: () => { let users = JSON.parse(localStorage.getItem('users') || '[]'); let filterList = users.filter((item: any) => item.uuid !== data.uuid); localStorage.setItem('users', JSON.stringify(filterList)); this.list = filterList } }); }
我们找到删除的数据,将其剔除,重新缓存新的用户数据,并更新table
的用户列表数据。
So,到此为止,我们顺利完成了一个简单的项目。我们用Gif
图整体来看看。
【完】
更多编程相关知识,请访问:编程入门!!
The above is the detailed content of Angular + NG-ZORRO quickly develop a backend system. For more information, please follow other related articles on the PHP Chinese website!