前端框架中的数据交互与组件开发:Angular与React实战
立即解锁
发布时间: 2025-08-20 01:09:30 阅读量: 1 订阅数: 2 


JavaScript入门与现代开发指南
### 前端框架中的数据交互与组件开发:Angular与React实战
#### 1. Angular 中数据从前端传递到 Node
前端部分借助 Bootstrap 搭建页面结构与表单样式,无需编写自定义 CSS。利用 Angular 的指令,可将 HTML 模板的数据绑定到 Typescript 组件代码,并检测表单提交按钮的点击事件。
之前创建了从本地 MySQL 数据库检索数据的服务,现在需在服务中创建新函数,将信息发送回 Node,服务器接收数据并插入数据库。
操作步骤如下:
1. 为 Express 应用添加 `body-parser` 库,在命令行执行:
```bash
npm install body-parser –save
```
该库使 Node 能在 Angular 发起 POST 请求时接收数据。
2. 更新 `app.js` 文件:
```javascript
const bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
```
3. 打开 `controllers` 文件夹中的 `boroughs.js` 文件,添加处理 POST 请求的能力:
```javascript
router.post('/', (req, res) => {
let boroughName = req.body.boroughName;
let state = req.body.state;
let records = {name: boroughName, state: state};
pool.query('INSERT INTO boroughs SET ?', records, (error, results) => {
if (error) throw error;
});
});
```
4. 创建代理,让 Angular 应用与 Node 服务器通信。更新 `borough.service.ts` 文件,添加 `addBorough` 函数:
```typescript
addBorough(value) {
return this.http.post('/boroughs', value, value);
}
```
5. 更新 `list-boroughs.component.ts` 文件中的 `submitBorough` 函数:
```typescript
submitBorough(value) {
//console.log(value);
this.boroughService.addBorough(value).subscribe((results) => {
console.log(results);
});
}
```
6. 为了在页面上获取新数据,将 `ngOnInit` 中的函数移到 `getBoroughs` 函数:
```typescript
getBoroughs(){
this.boroughService.getBoroughs().subscribe((data) => {
this.results = data;
});
}
```
7. 更新 HTML 模板,添加新行与按钮:
```html
<div class="row">
<div class="col-1">
<button class="btn btn-primary" (click) = 'getBoroughs()'>Get Boroughs</button>
</div>
<div class="col-11">
<div *ngFor = "let result of results">
id = {{ result.id }}
name = {{ result.name }}
state = {{ result.state }}
</div>
</div>
</div>
```
#### 2. React 应用的创建与组件开发
要使用 React 完成类似功能,首先创建 React 应用。操作步骤如下:
1. 全局安装 `create-react-app`:
```bash
npm install -g create-react-app
```
2. 创建新的 React 应用:
```bash
npx create-react-app my-app
```
3. 启动应用:
```bash
cd my-app
npm start
```
创建组件的步骤:
1. 创建 `components` 文件夹,在其中创建 `boroughs` 文件夹和 `boroughs.js` 文件。
2. 在 `boroughs.js` 文件中创建基本 React 组件:
```javascript
import { Component } from 'react';
export class Boroughs extends Component {
render() {
```
0
0
复制全文
相关推荐









