gpt4 book ai didi

Angular 7 PATCH方法将元素添加到列表

转载 作者:行者123 更新时间:2023-12-04 01:47:29 25 4
gpt4 key购买 nike

我应该如何编写允许我在数组中添加和删除数组项的 PATCH 方法?

元素类别:

export class ItemClass {
constructor(public person: string, public name: string, public quantity: number, public price: number){}
}

菜单模型:

    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);
}

(来自 https://stackoverflow.com/a/54679303/479251)

最佳答案

在后端补丁方法的更多细节之后,这里有一个(粗略的)示例,说明如何做到这一点。

您没有为 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 端点,并相应地使用 HttpClient Angular 服务中的 patch 方法,以及预期的 url 和内容。

现在,您必须添加逻辑以使用正确的参数发送请求。

关于Angular 7 PATCH方法将元素添加到列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54684861/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com