Angularjs Resource URL

I am starting with AngularJS and cannot find my error in this code

var myCarResource = $resource('cars/:carId', { carId:'@id' }); var car = myCarResource.get({id:'abc'}); 

Expected URL: .../cars/abc

Called URL: .../cars?id=abc

I am using angularjs v1.2.24

Can anyone help me? Thanks

+5
source share
1 answer

As stated in the $ resource paramDefaults :

Given the pattern / path /: verb and the parameter {verb: 'greet', the greeting: "Hello"} leads to the URL / path / greet? helutation = Hello.

If the parameter value has the @ prefix, then the value for this parameter will be extracted from the corresponding property on the data object (provided when the action method is called) . For example, if the defaultParam object is {someParam: '@someProp'}, then the value of someParam will be data.someProp

This means that any verb defined in the parameterizd URL that matches the keys defined in the default parameters of the $resource parameter or the parameters of the $resource class (get, save, etc.) will have the corresponding value of this key replace the verb in url. The designation '@', on the other hand, was not properly explained in this context, it should have been:

If the parameter value has the @ prefix, then the value for this parameter will be extracted from the corresponding property on the data object (provided when calling the instance method).

Instance action methods ($ get, $ save, $ delete, etc.) are methods that are used for data objects obtained using the behavior methods of the $resource class. They are usually useful when querying a chain with the same resources.

EXAMPLE DEMO

Suppose your cars/abc returns a json response:

 { "id": "abc" } 

Read the comments showing the responses of each action method call.

 var myCarResource = $resource('cars/:carId', { carId:'@id' }); // This sends a GET request '/cars/?id=abc myCarResource.get({id:'abc'}); // This sends a GET request '/cars/abc' myCarResource.get({carId:'abc'}); // returns {"id": "abc"} myCarResource.get({carId:'abc'}).$promise.then(function(car) { // sends a POST request '/cars/abc', it replaces the :carId verb from the // @id notation you have defined in the parameter default. It also sends, // other parameter defaults defined with '@' that are defined as verbs in the url. car.$save(); }); 
+5
source

Source: https://habr.com/ru/post/1202632/


All Articles