环境准备
准备angular项目环境、加载网络服务
已经创建了一个angular项目,项目自动生成的package.json文件的内容:
{
"name": "ng-pro1",
"version": "0.0.0",
"scripts": {
"ng": "ng",
"start": "ng serve",
"build": "ng build",
"watch": "ng build --watch --configuration development",
"test": "ng test"
},
"private": true,
"dependencies": {
"@angular/animations": "^18.1.0",
"@angular/common": "^18.1.0",
"@angular/compiler": "^18.1.0",
"@angular/core": "^18.1.0",
"@angular/forms": "^18.1.0",
"@angular/platform-browser": "^18.1.0",
"@angular/platform-browser-dynamic": "^18.1.0",
"@angular/router": "^18.1.0",
"rxjs": "~7.8.0",
"tslib": "^2.3.0",
"zone.js": "~0.14.3"
},
"devDependencies": {
"@angular-devkit/build-angular": "^18.1.4",
"@angular/cli": "^18.1.4",
"@angular/compiler-cli": "^18.1.0",
"@types/jasmine": "~5.1.0",
"jasmine-core": "~5.1.0",
"karma": "~6.4.0",
"karma-chrome-launcher": "~3.2.0",
"karma-coverage": "~2.2.0",
"karma-jasmine": "~5.1.0",
"karma-jasmine-html-reporter": "~2.1.0",
"typescript": "~5.5.2"
}
}
然后使用命令ng g c myc02
创建一个新的组件:
项目的app.module.ts文件中加载了网络服务:
在根组件中将app-myc02组件展示出来:
用json-server快速搭建一个mock服务
在项目根目录下面新建一个文件夹server,里面放一个存放数据的json文件:
运行npm i -D json-server
命令安装json-server。
在package.json文件中增加自定义命令:
运行npm run server
启动json-server服务:
在浏览器中验证,已经可以正常访问:
使用网络服务
发送一个POST请求:不带可选参数
修改组件myc02的myc02.component.ts文件,内容如下:
到浏览器控制台查看网络请求,已经发送成功:
发送一个POST请求:带可选参数,并将返回结果展示到页面上
组件的myc02.component.ts文件的内容:
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Component } from '@angular/core';
import { v4 as uuidv4 } from 'uuid';
@Component({
selector: 'app-myc02',
templateUrl: './myc02.component.html',
styleUrl: './myc02.component.css'
})
export class Myc02Component {
res: Result = {
date: '',
id: '',
money: 0,
type: ''
}
constructor(public http: HttpClient) { }
ngOnInit(): void {
// POST请求:地址和参数分开传递
// url代表请求地址,body代表请求参数,options代表请求设置
const url = 'http://localhost:8888/ka'
const testData = {
type: 'pay',
money: -20,
date: new Date(),
id: uuidv4()
}
const options = {
headers: new HttpHeaders({
'content-type': 'application/json'
})
}
// post(url, body, options)方法有三个参数
this.http.post<Result>(url, testData, options).subscribe(res => {
console.log(res)
this.res = res
})
}
}
interface Result {
date: string
id: string
money: number
type: string
}
组件的myc02.component.html文件:
页面展示: