[嗨,我正在一个项目中,我需要保存3个文本框字段。我很难找到如何用json正文发布。这是我到目前为止所拥有的。我一直在网上寻找点点滴滴,我很困惑。
onClickMe() {
this.dataService.saveOrder(this.order);
}
saveOrder (order: order): Observable<order> {
const href = 'http://localhost:7000/api/SaveOrder';
const config = { headers: new HttpHeaders().set('Content-Type', 'application/json') }
return this.httpClient.post<order>(href, order, config)
.pipe(
catchError(this.handleError('updateOrder', order))
);
}
export interface Order {
id: number;
name: string;
status: string;
}
因此,我假设您实际上并不需要设置标题,并且在此示例中省略它们,在某些情况下,您会说实话,但我会说大多数情况下省略。
首先,我要对您的函数进行更恰当的命名,onClickMe的实际功能非常晦涩,这既为您的利益,也为他人和他人在阅读您的代码时带来的好处,当您回来时,它会对您有很大帮助一些您几个月没有读的旧代码!
Component
saveOrderToDB(newOrder: Order): void{
this.orderService.saveNewOrder(newOrder).subscribe((response) => {
console.log('Succesfully posted', newOrder)
})
}
服务
url = 'http://localhost:7000/api/' // Use this as your base url across all http methods within your service and append the extra parts such as the SaveOrder within the methods themselves
saveOrderToDB(newOrder: Order): Observable<Order>{
this.orderService.saveNewOrder(newOrder).subscribe((response) => {
console.log('Succesfully posted', newOrder)
// Or you can log the response, response.message ect depending on what the backend returns
console.log(response);
})
}
老实说,Angular文档是掌握http服务的重要渠道-https://angular.io/guide/http