上节的最后我们展现了一个相当low的测试,在进行用户新增时不旦没有任何提示,并且还需要我们手动的输入链接来完成测试功能,这明显是接受不了的。 # 添加新增按钮 teacher/teacher-index.component.html ``` <router-outlet></router-outlet> <a routerLink="./add➊">新增</a> ✚ <table> ``` * ➊ 注意:此处我们使用的为`./add`,而不是`/add`。 # 添加跳转 teacher/teacher-add.component.ts ``` constructor(private httpClient: HttpClient, private appComponent: AppComponent, private router: Router ✚) { } this.httpClient.post(url, teacher) .subscribe(() => { console.log('添加成功'); this.appComponent.ngOnInit(); this.router.navigate(['./']➊); ✚ }, (response) => { console.error('请求发生错误', response); }); ``` * ➊ 此处我们使用的是`./`,而不是`/`。 # 去测试痕迹 在生产环境中,在V层中直接打印数据会严重影响用户的体验。 teacher-add.component.html ``` <pre>{{name}} {{username}} {{email}} {{sex}}</pre> ✘ ``` teacher-edit.component.html ``` <pre>{{teacher | json}}</pre> ✘ ``` # 定制报错信息 当前代码当http请求发生错误时,直接打印到了控制台。这对于开发而言无所,但做为用户就接受不了了。我们在C层定义一个`message`,然后在V层来显示它。 teacher-add.component.ts ```js export class TeacherAddComponent implements OnInit { name: string; username: string; email: string; sex: boolean; message = ''; ✚ ... /** * 显示错误信息。1.5秒后关闭显示 * @param message 错误信息 */ public showMessage(message = '发生错误' ➊): void { this.message = message; setTimeout(() => { ➋ this.message = ''; }, 1500); } this.httpClient.post(url, teacher) .subscribe(() => { this.appComponent.ngOnInit(); this.router.navigate(['./']); }, (response) => { this.showMessage('请求发生错误'); ✚ console.error('请求发生错误', response); }); ``` * ➊ 为message设置默认值。 * ➋ setTimeout()是一个内置函数,它接收两个参数: `function, number`,表示在`number`毫秒后执行`function`函数。 teacher-add.component.html ``` <h4 *ngIf="message">{{message}}</h4> ✚ <form id="teacherAddForm" (ngSubmit)="onSubmit()"> <div> ``` ** 请自行完成教师编辑的错误提示部分** ## 测试 ![](https://img.kancloud.cn/31/62/3162b8a78bbec4b28ff6572a690711ad_728x310.gif) # 参考文档 | 名称 | 链接 | 预计学习时长(分) | | --- | --- | --- | | 源码地址 | [https://github.com/mengyunzhi/spring-boot-and-angular-guild/releases/tag/step2.6.2](https://github.com/mengyunzhi/spring-boot-and-angular-guild/releases/tag/step2.6.2) | - |