📅  最后修改于: 2023-12-03 14:54:07.620000             🧑  作者: Mango
在 Web 开发中,CRUD 操作是非常常见的。CRUD 操作是指“创建(Create)、读取(Read)、更新(Update)、删除(Delete)”四个操作,是大部分 Web 应用程序的核心操作。为了实现这些功能,通常使用平均堆栈(MEAN Stack)开发。
平均堆栈是一种用于开发 Web 应用程序的技术栈,其中包含四个主要组件:
平均堆栈的每个组件都有其独特的功能和优势。MongoDB 提供了灵活性和可伸缩性,可以更轻松地存储和检索数据。Express 是一个快速且简单的框架,可以快速构建 API 接口。Angular 提供了一个现代化的用户界面,可以为应用程序提供更好的用户体验。而 Node.js 允许您使用 JavaScript 编写服务器端代码,并提供了非常快速的 I/O 操作,从而提高了应用程序的性能。
下面是一个使用平均堆栈开发的 CRUD 应用程序示例。
在 MongoDB 中,数据存储为文档(document),使用 JSON 格式表示。在本文中,我们使用一个 CPU 制造商的模型来演示使用平均堆栈进行 CRUD 操作。
// cpu.model.js
const mongoose = require('mongoose');
const CPUSchema = new mongoose.Schema({
manufacturer: {
type: String,
required: true
},
model: {
type: String,
required: true
},
speed: {
type: Number,
required: true
}
});
module.exports = mongoose.model('CPU', CPUSchema);
使用 Express 框架,我们可以很容易地构建后端 API,使其能够执行 CRUD 操作。在本例中,我们将使用以下路由:
GET /cpu
:获取所有 CPU 记录。GET /cpu/:id
:通过 ID 获取单个 CPU 记录。POST /cpu
:创建新的 CPU 记录。PUT /cpu/:id
:通过 ID 更新 CPU 记录。DELETE /cpu/:id
:通过 ID 删除 CPU 记录。// cpu.route.js
const express = require('express');
const router = express.Router();
const CPU = require('../models/cpu.model');
// GET all CPUs
router.get('/', async (req, res) => {
try {
const cpus = await CPU.find();
res.json(cpus);
} catch (err) {
res.json({ message: err });
}
});
// GET a single CPU
router.get('/:id', async (req, res) => {
try {
const cpu = await CPU.findById(req.params.id);
res.json(cpu);
} catch (err) {
res.json({ message: err });
}
});
// CREATE a new CPU
router.post('/', async (req, res) => {
const cpu = new CPU({
manufacturer: req.body.manufacturer,
model: req.body.model,
speed: req.body.speed
});
try {
const savedCPU = await cpu.save();
res.json(savedCPU);
} catch (err) {
res.json({ message: err });
}
});
// UPDATE a CPU
router.put('/:id', async (req, res) => {
try {
const updatedCPU = await CPU.updateOne(
{ _id: req.params.id },
{ $set: {
manufacturer: req.body.manufacturer,
model: req.body.model,
speed: req.body.speed
}
}
);
res.json(updatedCPU);
} catch (err) {
res.json({ message: err });
}
});
// DELETE a CPU
router.delete('/:id', async (req, res) => {
try {
const removedCPU = await CPU.deleteOne({ _id: req.params.id });
res.json(removedCPU);
} catch (err) {
res.json({ message: err });
}
});
module.exports = router;
使用 Angular 框架,我们可以轻松构建现代化的用户界面,使用户能够轻松地执行 CRUD 操作。在本例中,我们将使用以下组件:
app.component.html
:呈现 CPU 订单列表。app.component.ts
:从后端 API 获取 CPU 数据,并允许用户执行 CRUD 操作。add-cpu.component.html
:呈现创建新 CPU 的表单。add-cpu.component.ts
:处理创建新 CPU 的表单。<!-- app.component.html -->
<div *ngFor="let cpu of cpus">
<h3>{{ cpu.manufacturer }} {{ cpu.model }}</h3>
<ul>
<li>Speed: {{ cpu.speed }}</li>
</ul>
<button (click)="editCPU(cpu)">Edit</button>
<button (click)="deleteCPU(cpu._id)">Delete</button>
</div>
<div *ngIf="addingCPU">
<h3>Create a new CPU</h3>
<form (submit)="addCPU()">
<label>Manufacturer</label>
<input [(ngModel)]="newCPU.manufacturer" name="manufacturer" required />
<label>Model</label>
<input [(ngModel)]="newCPU.model" name="model" required />
<label>Speed</label>
<input [(ngModel)]="newCPU.speed" name="speed" required />
<input type="submit" value="Save" />
<button (click)="cancelAdd()">Cancel</button>
</form>
</div>
<button (click)="showAddCPU()">Add CPU</button>
// app.component.ts
import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
cpus: any = [];
addingCPU: boolean = false;
newCPU: any = {};
constructor(private http: HttpClient) {}
ngOnInit() {
this.http.get('/api/cpu').subscribe((data: any) => {
this.cpus = data;
});
}
showAddCPU() {
this.addingCPU = true;
}
cancelAdd() {
this.addingCPU = false;
this.newCPU = {};
}
addCPU() {
this.http.post('/api/cpu', this.newCPU).subscribe((data: any) => {
this.cpus.push(data);
this.addingCPU = false;
this.newCPU = {};
});
}
editCPU(cpu: any) {
// TODO: Implement edit functionality
}
deleteCPU(cpuId: any) {
this.http.delete(`/api/cpu/${cpuId}`).subscribe((data: any) => {
const index = this.cpus.findIndex((cpu: any) => cpu._id === cpuId);
this.cpus.splice(index, 1);
});
}
}
<!-- add-cpu.component.html -->
<h3>Create a new CPU</h3>
<form (submit)="onFormSubmit()">
<div>
<input [(ngModel)]="cpu.manufacturer" name="manufacturer" placeholder="Manufacturer" required />
</div>
<div>
<input [(ngModel)]="cpu.model" name="model" placeholder="Model" required />
</div>
<div>
<input [(ngModel)]="cpu.speed" name="speed" placeholder="Speed" required />
</div>
<button type="submit">Save</button>
</form>
// add-cpu.component.ts
import { Component, EventEmitter, Output } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'app-add-cpu',
templateUrl: './add-cpu.component.html',
styleUrls: ['./add-cpu.component.css']
})
export class AddCpuComponent {
cpu: any = {};
@Output() cpuAdded = new EventEmitter<any>();
constructor(private http: HttpClient) {}
onFormSubmit() {
this.http.post('/api/cpu', this.cpu).subscribe((data: any) => {
this.cpu = {};
this.cpuAdded.emit(data);
});
}
}
使用平均堆栈可以为您的 Web 应用程序提供各种优势,例如更快的开发速度、更高的性能和更简单的维护。在本示例中,我们演示了如何使用平均堆栈开发一个简单的 CRUD 应用程序。