$update PUT method in Angular?

2019-09-12 23:54发布

问题:

I couldn't find any examples of using an $update PUT method in Angular when using ui-router instead of ngRoute for routing. Is an $update PUT method possible when using ui-router?

回答1:

The $update method in the example you linked in the question comments has nothing to do with $routeParams or $stateParams. Those (in most cases) just refer the parameters that are present within the url.

As an example, if you declared a url in your config as: /#/foo/:id/bar and you visited the url: /#/foo/5/bar?hello=world&verified=1 then $routeParams and $stateParams would be an object that looks like:

{id: 5, hello: "world", verified: "1"}

Note: In the case of $stateParams, I think the url in the config might need to be declared as: /foo/:id/bar?hello&verified

As for the $update method and PUT requests, these are related to the angular-resource module. You'll notice from the example you cited that a service (factory) was declared that makes use of the $resource service. if you take a look at the docs specifically under the Returns section you'll see that the $resource service will return:

A resource "class" object with methods for the default set of resource actions optionally extended with custom actions. The default set contains these actions:

{'get':    {method:'GET'},
 'save':   {method:'POST'},
 'query':  {method:'GET', isArray:true},
 'remove': {method:'DELETE'},
 'delete': {method:'DELETE'} };

It further states:

The actions save, remove and delete are available on it as methods with the $ prefix.

So $save, $remove, $delete are avaiable but no $update. This is why the service in the example has the line:

...
'update': { method: 'PUT'},
...

It's meant to extend these default set of actions so that $update will be available as a method on the objects and it will use the HTTP PUT method instead of GET/POST/DELETE like the others.

I sugggest you do further reading on $routeParams, $stateParams and ngResource but hopefully the distinction between them is clear.