【发布时间】:2021-12-03 19:25:45
【问题描述】:
我想了解如何在 Angular 中调用 Http.post 方法。我正在尝试使用某些输入字段构建一个表单。一旦用户点击 UI 上的提交按钮,它就会调用一个服务(用 springboot 编写)将记录插入数据库。虽然我的 springboot 服务运行良好,但我无法从 Angular 正确调用它。
services.ts:
export class MFinService {
constructor(private http: HttpClient ) { }
public addRecord(networth : any){
return this.http.post<any>("http://localhost:8080/networth" , networth);
}
}
component.ts:
export class NetworthHomeComponent implements OnInit {
constructor(private mFinService : MFinService) { }
ngOnInit(): void {
}
// Reactive cardForm
cardForm = new FormGroup({
account : new FormControl(),
ppf : new FormControl(),
nps : new FormControl(),
pf : new FormControl(),
stocks : new FormControl(),
mf : new FormControl(),
online : new FormControl()
});
public submitForm(){
console.log(this.cardForm.value);
this.mFinService.addRecord(this.cardForm.value).subscribe(
(data : any) => {
console.log(data);
}
)
}
}
Springboot 控制器类:
@PostMapping("/networth")
public ResponseEntity<String> addNetworth(@RequestBody Networth networth){
int result = mFServices.addNetDetails(networth);
if(result > 0){
return ResponseEntity.status(HttpStatus.OK).body("A new records has been inserted !");
}
return null;
}
Springboot DTO 类:
错误:
在数据库中插入记录:
来自网络标签的请求和响应:
【问题讨论】:
-
正在发送的对象的名称在数据库中似乎不匹配,它们在
@RequestBody Networth networth中是否具有相同的名称?例如,角度帐户与数据库中的帐户数量 -
状态为200 OK,所以错误可能与响应有关,无法解析为JSON。检查网络选项卡,看看实际响应是什么。
-
添加了相同的屏幕截图。发生这种情况是因为响应是字符串格式,而 Angular 期望的是 json 格式吗?
标签: angular http-post spring-batch