3

How should I write the PATCH method that allows me to add and remove items of an array inside an array?

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

I have a menu component and a menu service. I need a patch method that adds elements to the ItemClass[] array inside Menu and is able to remove them as well.

The API method looks like :

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

(from https://stackoverflow.com/a/54679303/479251)

14
  • Not clear to me what you're asking Commented Feb 14, 2019 at 7:09
  • I need a PATCH API method that can add and remove elements of the ItemClass[] array, which is a parameter of the Menu. Commented Feb 14, 2019 at 7:11
  • 1
    I think you need to go back to the person who instructed you to do this, and ask for some more explanation. Commented Feb 14, 2019 at 7:27
  • I should probably provide more data. It's already a big code base, i've got tons of things working (GET, POST, DELETE requests) I've got more classes but they aren't relevant to this. Commented Feb 14, 2019 at 7:34
  • An array is an array everywhere. The only you need is check if is null before use push, or slice, e.g. if (!mymenu.items) {mymenu.items=[]} Commented Feb 14, 2019 at 7:35

1 Answer 1

4

After the additional details on the backend's patch method, here's a (crude) example of how you could do it.

You haven't specified a version for Angular, so I will suppose you are using last version (7), and 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.

  /* .... */
}     

Of course, this is the basic "Proof of concept" to get you started, to adapt to your need and the overall architecture of your Angular app.

As you can see, all I did was read the API endpoints, and use the patch method from the HttpClient Angular service accordingly, with the expected url and content.

Now, you have to add the logic to send the request with the correct parameters.

Sign up to request clarification or add additional context in comments.

18 Comments

alright, I'll try that one out. What should my menu component method look like? The one that i'll bind to the (click)? Thanks for this, I'll try it out as soon as i get the answer about the final method for the component. Yes, I'm using the latest version.
@soulzap I don't really know how to answer this, I don't how what your page is suppose to look like, what is the behavior, etc... That depends on your specifications. Basically, you should have a method that, when clicked, create / read the 'item' object to add, and call the method I wrote above. Also, you may want to refresh the list of displayed item once the request is ended.
maybe you can use StackBlitz to create something that looks like to what you want to do
i simply need to create a function that's going to activate whenever a button is clicked. The function implements the PATCH method. Hopefully you understand what I'm trying to say. For example, this is my getMenu GET method: getMenu(id: number): Observable<MenuModel>{ const url = ${this.menusUrl}/${id}; return this.http.get<MenuModel>(url) } ____ getMenu(): void { const id = +this.route.snapshot.paramMap.get('id'); this.menuService.getMenu(id) .subscribe(menu => this.menu = menu); } _____ The latter is the function for the button click event.
google-chrome --disable-web-security --user-data-dir launching the chrome that way, solved it. It's for development purposes only so that's good enough for me. Thanks for everything man!
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.