0

I'm trying to make a call to an MVC Web API using angular 2. The endpoint I have looks like this:

[HttpDelete]
[Route("DeleteMe")]
public ActionResult DeleteItems([FromQuery] string objectId, [FromBody] int[] toDelete) {
    //logic
}

And I can test this using postman, where I set a body using the content type 'application/json', and enter the following data.

[1,2,3]

This works just fine. However I cannot recreate this call with angular 2. I am using HttpClient to make my calls, and have code similar looking to this:

public callDeleteItems(objId: number, toDelete: number[]) {
    var serviceEndpoint = "endpoint here?objectId=" + objId;
    const params = new HttpParams().set("toDelete", JSON.stringify(toDelete));
    this.http.request('delete', serviceEndpoint, {
        params: params
    }).subscribe();
}
2
  • Please take a look at this : stackoverflow.com/questions/16374954/… Commented Feb 16, 2018 at 9:46
  • Much common scenario for DELETE is to have delete ids as query parameter ([FromUri]). Otherwise see @RameshRajendran link. Commented Feb 16, 2018 at 9:48

1 Answer 1

1

You have to use URLSearchParams

Something like this to generate your URL

public getURL(objId: number, toDelete: number[]): string {
    const urlParams: URLSearchParams = new URLSearchParams();
    urlParams.set('objectId', objId.toString());
    toDelete.forEach(n => urlParams.append('toDelete', n.toString()));
    return '/endpoint?' + urlParams.toString();
}

When you have to send an array, you have to use the append method

Example:

this.getURL(12, [1, 2, 3]);

Will generate the url as

/endpoint?objectId=12&toDelete=1&toDelete=2&toDelete=3

Your web API controller action should be

[HttpDelete]
[Route("DeleteMe")]
public ActionResult DeleteItems([FromUri] string objectId, [FromUri] int[] toDelete) {
    //logic
}

Demo

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.