Behrooz
Behrooz

Reputation: 1965

Why this angular $http.put parameter won't get passed?

I am facing a very weird case in my angularjs app. In a factory, the following code works properly:

$http.put(apiBase + 'delete?id='+orderId);

Which obviously connects to an api to perform a PUT operation (it is called "delete" here but it actually only updates a flag in the record).

But the same code, when written this way, does not work:

$http.put(apiBase + 'delete', {
    params: {
      id: orderId
    }
  }
);

Which is funny, because I am using the exact same syntax in some other factories to hit similar APIs and they work!

Upvotes: 1

Views: 679

Answers (2)

Josh Darnell
Josh Darnell

Reputation: 11433

When using $http.put, you don't need to wrap your data in the config object. You can pass the data object directly, and then omit the third parameter:

$http.put(apiBase + 'delete', { id: orderId });

Your other factories probably work with the syntax stated in your question because you are making $http.get or $http.delete requests.

I have found that this slightly-different API for the various "shortcut" methods to be confusing enough that I almost think it's better to avoid them altogether. You can see the differences from the documentation where get and delete have two parameters:

get(url, [config]);
delete(url, [config]);

and most of the other shortcut methods have three:

post(url, data, [config]);
put(url, data, [config]);

Note that the [config] object is defined further up on that documentation page, which is where it defines that "params" property:

params – {Object.} – Map of strings or objects which will be serialized with the paramSerializer and appended as GET parameters.

Upvotes: 1

keithm
keithm

Reputation: 958

I believe this is because the second argument of $http.put() is a data object, not a config object. You are passing a config object as the second parameter.

You could try:

$http.put(apiBase + 'delete', null, {
    params: {
      id: orderId
    }
  }
);

https://docs.angularjs.org/api/ng/service/$http#put

Upvotes: 2

Related Questions