我应该如何编写PATCH方法,使我可以在数组内部添加和删除数组的项目?
ItemClass:
export class ItemClass {
constructor(public person: string, public name: string, public quantity: number, public price: number){}
}
MenuModel:
import { ItemClass } from './item.model';
export class MenuModel {
id: number;
name: string;
items: ItemClass[];
constructor( id: number, name: string, items: ItemClass[]){
this.id = id;
this.name = name;
this.items = items;
}
}
我有一个菜单组件和一个菜单服务。我需要一个修补方法,该方法可以将元素添加到Menu内的ItemClass []数组中,并且也可以将其删除。
API方法如下:
@PATCH
@Path("/add/{menuId}")
public void removeMenuItem(
@PathParam("menuId") final int menuId,
final Item item) { // Item represents the Request Body
final List<Item> items = this.menuRepository.get(menuId).getItems();
items.add(item);
}
答案 0 :(得分:1)
在有关后端的补丁方法的其他详细信息之后,这是一个如何做的粗略示例。
您尚未为Angular指定版本,所以我想您使用的是最新版本(7)和HttpClient
。
import { HttpClient } from '@angular/common/http';
/* ... */
export class YourComponentOrService {
// note : you will need to add HttpClientModule to the application module 'imports' and 'providers' sections
constructor(private http: HttpClient) {}
/* ...*/
// call this method when you want to add an item
public addItem(menuID: number, itemToAdd: ItemClass): void {
console.log('sending patch request to add an item');
this.http.patch(`example.com/add/{menuId}`, itemToAdd).subscribe(
res => {
console.log('received ok response from patch request');
},
error => {
console.error('There was an error during the request');
console.log(error);
});
console.log('request sent. Waiting for response...');
}
// as I could see on the linked Q&A, the delete method will be very similar
// only the url will use 'remove' instead of 'add', along with the item name, and no body.
/* .... */
}
当然,这是入门的基本“概念证明”,可以适应您的需求和Angular应用程序的总体架构。
如您所见,我所做的只是读取API端点,并相应地使用了patch
Angular服务中的HttpClient
方法,并带有预期的URL和内容。
现在,您必须添加逻辑以使用正确的参数发送请求。