在 angular 9 中使用 json body 创建 HTTP Post 的最佳方法
Best way to make an HTTP Post with json body in angular 9
您好,我正在做一个需要保存 3 个文本框字段的项目。
我很难找到如何使用 json body post。这是我到目前为止所拥有的。
一直在网上找零零碎碎的,一头雾水
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;
}
所以我假设你真的不需要设置 headers 并且在这个例子中省略它们,有一些用例你会但老实说我会说大多数情况下他们可以被排除在外。
首先,我会更恰当地命名您的函数 onClickMe 实际上它的作用非常模糊,这对您和阅读您的代码的其他人都有好处,您会惊讶地发现它在以下情况下有多大帮助你回到了一些你几个月没读过的旧代码!
组件
saveOrderToDB(newOrder: Order): void{
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);
})
}
服务
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
saveOrder(order: Order): Observable < Order > {
return this.http.post<Order>(`${this.url}SaveOrder`, order)
.pipe(
catchError(this.handleError('updateOrder', order))
)
}
此外,Angular 文档确实是掌握 http 服务的重要途径 - https://angular.io/guide/http
您好,我正在做一个需要保存 3 个文本框字段的项目。 我很难找到如何使用 json body post。这是我到目前为止所拥有的。 一直在网上找零零碎碎的,一头雾水
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;
}
所以我假设你真的不需要设置 headers 并且在这个例子中省略它们,有一些用例你会但老实说我会说大多数情况下他们可以被排除在外。
首先,我会更恰当地命名您的函数 onClickMe 实际上它的作用非常模糊,这对您和阅读您的代码的其他人都有好处,您会惊讶地发现它在以下情况下有多大帮助你回到了一些你几个月没读过的旧代码!
组件
saveOrderToDB(newOrder: Order): void{
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);
})
}
服务
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
saveOrder(order: Order): Observable < Order > {
return this.http.post<Order>(`${this.url}SaveOrder`, order)
.pipe(
catchError(this.handleError('updateOrder', order))
)
}
此外,Angular 文档确实是掌握 http 服务的重要途径 - https://angular.io/guide/http