更新数据时,我们需要给后台提供两项信息:1. 我们要更新哪个教师;2. 更新后的教师的数据应该是什么值。 # RESTful web service 在前后台的交互过程中,我们前面规定了使用`GET`方法请求`/Teacher`地址来获取教师的全部数据;规定了使用`GET`方法请求`/Teacher/1`地址来获取教师ID为`1`的数据;规定了使用`POST`方法请求`/Teacher`地址来新增教师。其实这些都是在遵循`REST`规范。维基百科如是说: ***** **Representational state transfer**(**REST**) is a [software architectural](https://en.wikipedia.org/wiki/Software_architecture "Software architecture") style that defines a set of constraints to be used for creating [Web services](https://en.wikipedia.org/wiki/Web_service "Web service"). Web services that conform to the REST architectural style, called *RESTful* Web services, provide interoperability between computer systems on the [Internet](https://en.wikipedia.org/wiki/Internet "Internet"). RESTful Web services allow the requesting systems to access and manipulate textual representations of [Web resources](https://en.wikipedia.org/wiki/Web_resource "Web resource")by using a uniform and predefined set of [stateless](https://en.wikipedia.org/wiki/Stateless_protocol "Stateless protocol")operations. Other kinds of Web services, such as [SOAP](https://en.wikipedia.org/wiki/SOAP "SOAP")Web services, expose their own arbitrary sets of operations.[\[1\]](https://en.wikipedia.org/wiki/Representational_state_transfer#cite_note-1) ***** 上面大概是说REST是一种软件开发的风格(style),而符合这个风格的web服务呢,就是`RESTful Web services`。而我们前面进行前后台交互时的地址恰恰是按照该风格来制定的。该风格同时规定,进行数据的全部更新时,应该使用`put`方法,并在路径中传入要更新的`id`值以及在请求的数据中传入更新数据。所以我们制定接口规范如下: ``` PUT /Teacher/{id} ``` | Type | Name | Description | Schema | | ---- | ---- | ---- | ---- | | Path | id | 更新的教师ID | Long | | Body | teacher | 更新教师数据 | Teacher | 上述接口描述清晰的说明了请求的方法为`PUT`,请求的地址为`/Teacher/{id}` ,该地址中包括有路径变量`id` ,该值代表`更新的教师ID` 类型为 `Long`。同时接收请求主体(`Body`),类型为`Teacher`,代表`更新教师数据`。 # 更新数据 我们前面已经掌握了获取路径ID值的方法,又知道V层数据变更新将会实时的传递给C层,那么代码就简单了。 ``` constructor(private route: ActivatedRoute, private httpClient: HttpClient, private appComponent: AppComponent ①) { } /** * 提交表单更新数据 */ onSubmit(): void { const id = this.route.snapshot.paramMap.get('id'); const url = 'http://localhost:8080/Teacher/' + id; this.httpClient.put(url, this.teacher ➋) ➊ .subscribe(() => { console.log('更新成功'); this.appComponent.ngOnInit(); }, () => { console.error(`更新数据时发生错误,url:${url}`); }); } ``` * ➊ PUT方法与POST方法使用相同。第个参数传入URL信息,第二个参数传入请求主体。 * ➋ 由于this.teacher的值会随着用户在表单中的输入而实时变化,所以我们在此直接将this.teacher传给后台。 > 如果此时你心里不大清楚this.teacher对象的值,那么可以在使用它之前使用`console.log(this.teacher)`来将其打印到控制台来查看。 # 代码重构 代码重构是软件开发中非常重要的一环,可以说没有代码重构就没有优秀的项目。本着**不造重复的轮子**的原则,当相同的代码块、字符串在项目中出现了多次的时候,就需要思索此处代码是否需要重构了。当前`TeacherEditComponent`的代码如下: ```js import {Component, OnInit} from '@angular/core'; import {ActivatedRoute} from '@angular/router'; import {HttpClient} from '@angular/common/http'; import {AppComponent} from './app.component'; @Component({ templateUrl: './teacher-edit.component.html' }) export class TeacherEditComponent implements OnInit { public teacher: any = {}; constructor(private route: ActivatedRoute, private httpClient: HttpClient, private appComponent: AppComponent) { } ngOnInit(): void { const id = this.route.snapshot.paramMap.get('id'); ➊ const url = 'http://localhost:8080/Teacher/' + id; ➊ this.httpClient.get(url) .subscribe((data) => { this.teacher = data; }, () => { console.log(`请求 ${url} 时发生错误`); }); } /** * 提交表单 */ onSubmit(): void { const id = this.route.snapshot.paramMap.get('id'); ➊ const url = 'http://localhost:8080/Teacher/' + id; ➊ this.httpClient.put(url, this.teacher) .subscribe(() => { console.log('更新成功'); this.appComponent.ngOnInit(); }, () => { console.error(`更新数据时发生错误,url:${url}`); }); } } ``` * ➊ 在一个类中,相同的代码块出现了两次。 ## 方法一 ** 当在一个类中,相同的代码码出现了多次的时候,可以把该代码块抽离为该类的一个新方法。** TeacherEditComponent ``` /** * 获取与后台对接的URL */ getUrl(): string { const id = this.route.snapshot.paramMap.get('id'); return 'http://localhost:8080/Teacher/' + id; } ``` 然后在原方法中删除对应的代码段并调用新抽离的方法来获取需要的值。 ``` /** * 获取与后台对接的URL */ getUrl(): string { const id = this.route.snapshot.paramMap.get('id'); return 'http://localhost:8080/Teacher/' + id; } ngOnInit(): void { this.httpClient.get(this.getUrl()) ➊ .subscribe((data) => { this.teacher = data; }, () => { console.log(`请求 ${this.getUrl()➊} 时发生错误`); }); } /** * 提交表单 */ onSubmit(): void { this.httpClient.put(this.getUrl()➊, this.teacher) .subscribe(() => { console.log('更新成功'); this.appComponent.ngOnInit(); }, () => { console.error(`更新数据时发生错误,url:${this.getUrl()➊}`); }); } ``` * ➊ 调用新方法`getUrl()`来直接获取请求地址的值。 ## 方法二 方法一中`getUrl()`被执行了两次,且每次执行返回的结果必然相同。这种时候当该方法执行的逻辑简单、运算量不大、没有资源请求的时候是并没太大的问题的,但如果其逻辑复杂、运算量大或是有资源请求时,就会带来不必要的开销。所以:**当某个方法在多次调用的结果都是确定值时,应该保证该方法的运算只执行一次**,此时我们需要一个变量来缓存方法运算的值。 TeacherEditComponent ``` private url: string; ➊ /** * 获取与后台对接的URL */ getUrl(): string { if (this.url === undefined) { ➋ const id = this.route.snapshot.paramMap.get('id'); this.url = 'http://localhost:8080/Teacher/' + id; ➌ } return this.url; } ``` * ➊ 在类中定义私有变量`url`,设置类型为`string`。 * ➋ 当`this.url`没有被初始化时,说明该方法未经过运算。 * ➌ 将运算的结果缓存到`this.url`中。 此时,当该方法被第1次调用时将计算`url`值;当该方法被第二次调用时,将直接返回第1次调用时计算得到的值,不再重新计算。 # 测试 代码重构后进行测试,查看是否由于重构给项目带来的新的BUG。 # 参考文档 | 名称 | 链接 | 预计学习时长(分) | | --- | --- | --- | | 发起PUT请求 | [https://www.angular.cn/guide/http#making-a-put-request](https://www.angular.cn/guide/http#making-a-put-request) | 5 | | 源码地址 | [https://github.com/mengyunzhi/spring-boot-and-angular-guild/releases/tag/step2.4.4](https://github.com/mengyunzhi/spring-boot-and-angular-guild/releases/tag/step2.4.4) | - |