本小节,让我们完成klass模块中组件间的对接工作,以及较验前后台的对接效果。 # 组件对接 ### 增加新增班级链接 klass/index/index.component.html ``` <a routerLink="./add">新增班级</a> ✚ <form (ngSubmit)="onQuery()"> ``` **注意:** 是`./add`而不能是`/add`。 #### 测试 ![](https://img.kancloud.cn/c7/9d/c79d28161bda927b9317be3041515558_251x104.png) ### 新建后跳转到首页 klass/add/add.component.ts ```js constructor(private httpClient: HttpClient, private router: Router, ① private route: ActivatedRoute ①) { } onSubmit(): void { const url = 'http://localhost:8080/Klass'; const klass = new Klass(undefined, this.name.value, new Teacher(parseInt(this.teacherId.value, 10), undefined, undefined) ); this.httpClient.post(url, klass) .subscribe(() => { console.log('保存成功'); this.router.navigate([''], {relativeTo: this.route}); ✚ }, (response) => { console.log(`向${url}发起的post请求发生错误` + response); this.setMessage(AddComponent.errorMessage); }); } ``` 我们重新启动后台,并进行前后台对接测试: ![](https://img.kancloud.cn/d1/53/d153ca80cc35653f0793701f3b2b982c_401x380.gif) 由于前面在单元测试中我们已经下足了功夫,所以此次测试结果完美 😄 # 参考文档 | 名称 | 链接 | 预计学习时长(分) | | --- | --- | --- | | 源码地址 | [https://github.com/mengyunzhi/spring-boot-and-angular-guild/releases/tag/step3.3.7](https://github.com/mengyunzhi/spring-boot-and-angular-guild/releases/tag/step3.3.7) | - | | 相对导航 | [https://www.angular.cn/guide/router#relative-navigation](https://www.angular.cn/guide/router#relative-navigation) | 5 |