隨着教程的進行,除了感受一些單元測試和涉及到一些驗證方面的代碼有點難搞,發現其餘的功能代碼都仍是挺好弄明白的,以前教程上的文件都不是道去哪找,如今看見代碼就知道它大概在哪一個文件,相信再過不久,單元測試也能像以前的代碼那樣信手拈來。java
以前也算搞明白了先後臺對接的方式,無非就是前臺發送請求,後臺接收請求,返回想要的值,固然前提是前臺要訂閱,不然不發送請求,下面以學生的新增方法爲例
Student.service.tssql
public save(student: Student): Observable<Student> { const url = 'http://localhost:8080/Student'; return this.httpClient.post<Student>(url, student); }
student/add.component.ts瀏覽器
onSubmit(): void { console.log(this.formGroup.value); console.log(this.klass); this.student = this.formGroup.value; this.student.klass = this.klass; console.log(this.student); this.studentService.save(this.student).subscribe((student:Student) =>{ console.log(student); this.linkToIndex.nativeElement.click(); }) }
StudentController.javaapp
@PostMapping @ResponseStatus(HttpStatus.CREATED) public Student save(@RequestBody Student student){ return studentService.save(student); }
StudentServiceImpl.javaide
@Override public Student save(Student student) { this.studentRepository.save(student); return student; }
相對於新增數據使用的Post請求、更新數據使用的Put請求以及刪除使用的Delete請求來講,查詢數據使用的Get方法使用的十分普遍,甚至在一個實體類內要使用屢次,爲了區分,他們會加上一些參數,還多是一些路徑,可是,咱們沒有聲明前臺的請求就對應後臺的某個方法,舉個例子吧:post
@PostMapping("login") public boolean login(@RequestBody Teacher teacher){ return this.teacherService.login(teacher.getUsername(), teacher.getPassword()); }
昨天遇到這段代碼確實迷茫了,像以前的代碼,裏面放的都是參數,就像下面這樣,裏面放置了「id」這個參數,可是上面的是啥,一開始也覺得是參數,可是仔細看了前臺發現並無給它定義,這是憑空出現的一個「參數」,而後就蒙圈了,後來晚上請教了一下潘老師,發現這是個路徑,也就是說前臺必須訪問「http://localhost:8080/Teacher/login」才能和後臺完成數據的交互,而有「{}」的纔是參數。單元測試
@DeleteMapping("{id}") public void delete(@PathVariable Long id) { String sql = String.format("delete from teacher where id = %s" ,id); this.jdbcTemplate.update(sql); }
那麼問題來了,對於前面的add,edit以及delete方法來講,我沒有指定路由,可是它怎麼實現對接的呢。測試
有疑惑只靠想只不能解決問題的,就算真的猜明白了,本身也會保留懷疑的態度,只有親手實踐了,纔會信服
因爲代碼出現了一些問題,沒有辦法運行測試了,只能看代碼去理解了:this
public onSubmit(): void { const url = 'http://localhost:8080/Teacher'; const teacher = { name: this.name, username: this.username, email: this.email, sex: this.sex }; console.log(teacher); this.httpClient.post(url,teacher) .subscribe(() =>{ console.log('添加成功'); this.appComponent.ngOnInit(); this.router.navigate(\['./../'\],{relativeTo:this.route}); },(response)=>{ this.showMessage('請求發生錯誤'); console.log('請求發生錯誤',response); }); }
以上對應的是教師的新增方法,有參數的直接傳參數,沒參數的就是原路徑,之因此訪問index、add、edit、delele纔會實現對接,是由於前臺的設置,當點擊按鈕時跳轉到對應的路由時,纔會執行對應的方法,而登陸則是直接訪問url
login(username: string, password: string): Observable<boolean\>{ const url = 'http://localhost:8080/Teacher/login'; return this.httpClient.post<boolean\>(url,{username,password}); }
實現訪問的方法真的挺靈活的,就像上一次博客寫的新增成功後跳轉到首頁的方法,能夠直接定義路由跳轉,也能夠寫一個隱藏按鈕,模擬點擊跳轉,真的挺靈活的,本身的思惟仍是須要提高。
上週的瀏覽器大小寫區分問題總算獲得瞭解決,原本想搜英文,奈何本身的英語都還給了高中老師,找來找去在知乎上找到了一篇像樣的文章,也算找到了合理的解釋吧