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

标签 angular typescript rest api

我应该如何编写允许我在数组中添加和删除数组项的 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/

相关文章:

javascript - express-validator 两次返回验证错误

javascript - 类型 'campanha' 上不存在属性 'DisputaComponent[]' - Angular 2

javascript - @types/react 找不到名称 'HTMLDialogElement'

javascript - 如何批量插入CouchDB文档?

javascript - 使用 Typescript 或 javascript 动态获取类成员名称和值

angular - Angular2 中的一种数据绑定(bind)方式

angular - asp.net core prerender webpack 错误 : TypeError: Cannot read property 'filter'

javascript - 从@angular 2.4.9 升级到@angular 4.0.0 @angular/cli 后显示无效错误

java - 使用 Spring 保护用户帐户微服务

rest - 何时在 RESTful API 中使用路径参数与查询参数?