Angular完整项目开发11 - 增、删、改、查(CRUD)

经过前面的一些折腾,Angular前端系统的基础工作差不多了,现在轮到应用的核心内容之一:增、删、改、查。

以设备模块(device)为例。

1. 查询

device.service.ts

url = Global.commonURL + '/device';

getDevice():Observable<any> {
  return this.http.get(this.url, Global.commonHttpOptions); //commonHttpOptions是一些本项目特有的http header
}

device.component.ts

devices:Device[] = new Array;
  
ngOnInit(): void { 
   this.getDevice();
}

getDevice() {
    this.deviceService.getDevice().subscribe(
      (data:Device[])=>{ 
        this.devices = data;
        this.hightLightDevice(this.device);
      }
    );
}

device.component.html, Angular Material的Table

<div class="table-container">
  <table mat-table [dataSource]="devices" class="mat-elevation-z8" id="table" >

    <ng-container matColumnDef="id"> <!--这一列是id,隐藏-->
            <th mat-header-cell *matHeaderCellDef style="display:none;"></th>
            <td mat-cell *matCellDef="let device" style="display:none;"> {{device.id}} </td>
    </ng-container>

    <ng-container matColumnDef="index">
      <th mat-header-cell *matHeaderCellDef ></th>
      <td mat-cell *matCellDef="let i = index" class="col-index">{{i+1}}</td>
    </ng-container>

    <ng-container matColumnDef="no">
      <th mat-header-cell *matHeaderCellDef>编号</th>
      <td mat-cell *matCellDef="let device"> {{device.no}} </td>
    </ng-container>
  
    <ng-container matColumnDef="name">
      <th mat-header-cell *matHeaderCellDef>名称</th>
      <td mat-cell *matCellDef="let device"> {{device.name}} </td>
    </ng-container>
  
    <ng-container matColumnDef="deployTime">
      <th mat-header-cell *matHeaderCellDef>部署时间</th>
      <td mat-cell *matCellDef="let device"> {{device.deployTime}} </td>
    </ng-container>
  
    <tr mat-header-row *matHeaderRowDef="[ 'id', 'index','no', 'name', 'deployTime']"></tr>
    <tr mat-row *matRowDef="let device; columns: [ 'id', 'index','no', 'name', 'deployTime'];"
        (click)="selectRow(device)"
    ></tr>

  </table>
</div>

效果:

2. 增、改、删三个按钮

device.component.html, 三个按钮对应了edit()和delete()方法

 <div class="button-row"><!--css样式就不帖了,反正就是让三个按钮拍成一排靠右对齐-->
    <button mat-raised-button (click)="edit(0)"><mat-icon>add</mat-icon>新建</button>&nbsp;&nbsp;&nbsp;&nbsp;
    <button mat-raised-button color="primary" (click)="edit(1)"><mat-icon>create</mat-icon>修改</button>&nbsp;&nbsp;&nbsp;&nbsp;
    <button mat-raised-button color="warn" (click)="delete()"><mat-icon>remove</mat-icon>删除</button>&nbsp;&nbsp;&nbsp;&nbsp;
  </div>

效果:

 

3. 选中一条记录

device.component.ts,

//当前设备
device:Device = new Device();
//选中一行
selectRow(device:Device) {
    this.hightLightDevice(device);
    this.device = device;
}
//检查表格,匹配当前选中的项
hightLightDevice(device:Device){
    let table:HTMLTableElement = document.querySelector("#table");
    for(var i = 0; i < table.rows.length; i++){
        let row:HTMLTableRowElement = table.rows[i];
        row.style.backgroundColor = "white";
        if(row.cells[0].textContent.trim() == device.id.toString()){
          row.style.backgroundColor = "#DEDEDE";
        }
    }
}

效果:

 

4. 新增/修改

device.component.ts, 打开对话框EditDeviceDlg,当前device作为参数传入(新增就是一个空的device)

edit(op:number) {
    let obj = {};
    if(op == DT.OP_ADD){ //新增
      obj = { data: new Device() };
    }
    if(op == DT.OP_EDIT){ //修改
      if(this.device.id == null){ 
        this.dialog.open(Hint, {data:"请选择一条记录!"});
        return;  }
      obj = { data: this.device };
    }
    const dialogRef = this.dialog.open(EditDeviceDlg, obj); //对话框EditDeviceDlg
    dialogRef.afterClosed().subscribe(result => {
      if(result){
        this.getDevice();
      }else{
        this.restoreDevice();
      }
    });

  }
import { MatDialog, MatDialogRef,MAT_DIALOG_DATA} from '@angular/material/dialog';

//对话框
@Component({
  selector: 'edit',
  templateUrl: './dlg/edit.html',
})
export class EditDeviceDlg {
  constructor(
    private deviceService: DeviceService, 
    @Inject(MAT_DIALOG_DATA) public device: Device
  ) { }
  save() {
    this.deviceService.save(this.device).subscribe(
      (data:Device)=>{  }
    );
  }
}

device.service.ts

save(obj:any):Observable<any> {
    return this.http.post(this.url, obj, Global.commonHttpOptions);
}

对话框的html模板:

<h2 mat-dialog-title style="font-family: 微软雅黑;">{{device.id?"编辑":"添加"}} - 设备</h2>
<mat-dialog-content class="mat-typography">
 <p>
  <mat-form-field >
    <mat-label>编号</mat-label>
    <input matInput type="text" [(ngModel)]="device.no" id="inputNo">
  </mat-form-field>
</p>
  
  <p>
    <mat-form-field >
      <mat-label>名称</mat-label>
    <input matInput type="text" [(ngModel)]="device.name" id="inputName">
    </mat-form-field>
  </p>

<p>
  <mat-form-field >
  <mat-label>部署日期</mat-label>
  <input matInput [matDatepicker]="picker" [(ngModel)]="device.deployTime" [readonly]="true">
  <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
  <mat-datepicker #picker></mat-datepicker>
  </mat-form-field>
</p>

</mat-dialog-content>
<mat-dialog-actions align="end">
  <button mat-raised-button [mat-dialog-close]="false">取消</button>
  <button mat-raised-button [mat-dialog-close]="true"color="primary" cdkFocusInitial (click)="save()">保存</button>
</mat-dialog-actions>

效果:

5. 删除

device.component.ts

delete() {
    let obj = {data:"确实要删除吗?"}; //删除前的确认
    const dialogRef = this.dialog.open(Prompt, obj);
    dialogRef.afterClosed().subscribe(result => {
      console.log(`Prompt result: ${result}`);
      if(result){
        this.deviceService.delete(this.device.id).subscribe(
          (data:any)=>{ this.getDevice(); }
        );
      }
    });
 }

device.service.ts

delete(id:number) {
   return this.http.delete(this.url+"/" + id, Global.commonHttpOptions);
}

效果:

 

至此,增删改查基本完成。整体效果如下:

 

  • 4
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
Spring Boot 是一个流行的 Java Web 开发框架,它简化了构建企业级应用程序的流程。对于增删改查CRUD)操作,通常会涉及前端和后端的配合。在 Spring Boot 中,页面设计通常使用 HTML、Thymeleaf、Spring MVC 或者最近更流行的选择,如 React、Vue 或 Angular 结合 Spring Boot WebFlux。 1. **创建(Create)**: - 前端:使用模板引擎创建一个表单,用户输入新数据。可以利用 Bootstrap 或 Material-UI 等库美化界面。 - 后端:在 Spring Boot 控制器中,创建 POST 接口,接收前端提交的数据并调用相应的 service 方法保存数据。 2. **读取(Read)**: - 前端:展示列表页,可以通过 AJAX 请求向后端获取数据,也可以直接链接到详情页。 - 后端:提供 GET 请求接口,根据询参数返回对应的数据。 3. **更新(Update)**: - 前端:在详情页中显示已选中的数据,允许编辑并处理修后的表单数据。 - 后端:处理 PUT 或 PATCH 请求,更新指定的数据。 4. **除(Delete)**: - 前端:在列表页或详情页提供一个确认除的提示,通常有额外的安全措施防止误操作。 - 后端:处理 DELETE 请求,从数据库中除选定的数据。 相关问题-- 1. 在 Spring Boot 中,如何配置 RESTful API 来支持 CRUD 操作? 2. 如何在 Spring Boot 中集成前端模板引擎以展示表格数据? 3. 什么是 Thymeleaf 及其在 Spring Boot 页面设计中的作用? 4. 如何在 Spring Boot 中实现前端与后端的分页和排序功能?

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小鹰信息技术服务部

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值