How to send a resource collection using Restangular? - javascript

Let's say I want to send a DELETE request to a resource like /products and I want to delete multiple products.
The whole request would be to the following URI: /products/ids=1&ids=2&ids=3
How can I issue a request like the above one using Restangular?
For now, the issue is that customDELETE receives query string params using an object. Hence, it can't define the same parameter more than once...

Finally it was an easy one:
products.one().customDELETE(null, { ids: [1,2,3,5] } });

Related

Laravel resource route delete from axios

I would like to setup axios to delete a record using a resource route:
axios.delete('/job-management', this.deletedata).then((res)=>{
console.log(res);
})
For my routes I have:
Route::resource('job-management', "PositionsController", [ 'as' => 'jobs']);
Now, in my PositionsController I have:
public function destroy(Positions $positions) {
return $positions;
}
But the above always returns "method not allowed". How can I handle a delete request with the axios delete() method?
Laravel throws the MethodNotAllowedHttpException when we attempt to send a request to a route using an HTTP verb that the route doesn't support. In the case of this question, we see this error because the JavaScript code sends a DELETE request to a URL with the path of /job‑management, which is handled by a route that only supports GET and POST requests. We need to change the URL to the conventional format Laravel expects for resourceful controllers.
The error is confusing because it hides the fact that we're sending the request to the wrong URL. To understand why, let's take a look at the routes created by Route::resource() (from the documentation):
Verb URI Action Route Name
GET /job-management index job-management.index
GET /job-management/create create job-management.create
POST /job-management store job-management.store
GET /job-management/{position} show job-management.show
GET /job-management/{position}/edit edit job-management.edit
PUT/PATCH /job-management/{position} update job-management.update
DELETE /job-management/{position} destroy job-management.destroy
As shown above, URLs with a path component of /job-management are passed to the controller's index() and store() methods which don't handle DELETE requests. This is why we see the exception.
To perform a DELETE request as shown in the question, we need to send the request to a URL with a path like /job-management/{position}, where {position} is the ID of the position model we want to delete. The JavaScript code might look something like:
axios.delete('/job-management/5', this.deletedata).then((res) => { ... })
I've hardcoded the position ID into the URL to clearly illustrate the concept. However, we likely want to use a variable for the this ID:
let positionId = // get the position ID somehow
axios.delete(`/job-management/${positionId}`, this.deletedata).then((res) => { ... })
The URL in this form enables Laravel to route the DELETE request to the controller's destroy() method. The example above uses ES6 template string literals because the code in the question suggests that we're using a version of JavaScript that supports this feature. Note the placement of backticks (`) around the template string instead of standard quotation marks.
as I can see in your code above, you pass Positionseloquent as a parameter to destroy method but in your vueJS you don't pass this object. for that you would pass it like this :
axios.delete('/job-management/${id}').then((res)=>{
console.log(res);
})
and the id param inside the url of ur axios delete, it can object of data or any think.
i hope this help you

modify resource using restangular by making put on name not id

I have profile resource which has
profileName,
firstName ,
Lastname and
id
here profileName is unique and used as resource identifier and id is just a count.
To modify resource it accept put request on
http://localhost:9090/messanger/api/[profileName]
Now problem is whenever I'm making put request, it replace profile name with id. I am unable to make restangular put request on profileName.
Code is as follows.
$scope.editUser=function(id){
var profile=$scope.profiles[id];
$scope.profile=profile;
profile.save().then(function(res){
console.log(res);
});
}
It turn out that there was a problem with method which was handling put request at backend. Object I was passing has 4 properties in java code but when I was passing it from front end I was passing only 3. Previously I was trying
var items=Restanular.all("profiles").getList();
var item=items[i];
item.propertyName=New Value;
item.save();
This should have ideally work but I think it require some thing more as when I called save method it made a request on http://localhost:9090/messanger/api/
rather than making request on http://localhost:9090/messanger/api/[profileName]

how can I access to a specific json value in my returned data

I send a http GET request which returns JSON data in the following form. I am finding it impossible to access this data despite having no problems with example json that I create. I want to ideally take the array under wifi, and use this data to create a html table, but I think I can work out how to create the table if I could just access the actual elements of the data.
I have tried multiple methods to try and reach the first timestamp. I have tried:
var element = result.undefined.clients.wifi[0].timestamp;
but this returns an error that 'clients' can't be found.
I also tried:
var element = result.clients.wifi[0].timestamp; //and
var element = result.wifi[0].timestamp;
The JSON data returned to a variable is shown below:
result = undefined
{"sourceId":"idid","sourceType":"CLOUD_source","searchMeta":{"maxResults":4,"metricType":["clients"],"family":["wifi"],"Interval":"M1"},
"clients":{"wifi":
[{"timestamp":1424716920,"avg":3,"min":1,"max":4,"Count":8,"sCount":3,"sources":["x1","x2","x3","x4","x5","x6","x7","x8"]},{"timestamp":1424716980,"avg":2,"min":1,"max":3,"Count":4,"sCount":2,"sources":["x3","x4","x8","x4"]},{"timestamp":1424717160,"avg":2,"min":1,"max":3,"Count":9,"sCount":4,"sources":["x3","x4"]}]}}
The JSON data is invalid. If it is returned from a server, you need to go there and correct the data source, (if you have access to that).
Otherwise, perhaps notify the backend guy(s) about it.
If it is from a REST API, and you are "sure" that the server code should be error free, then check that you have supplied all the required parameters in the API request you are making.
I think your JSON is messed up. I ran it through JSONLint, and having the undefined at the beginning causes things to break.

Ext Js proxy pass parameter

I want to pass a parameter to my Store proxy to retrieve the right data from the server. I need to pass the parameter without the name prefix and just the value.
Instead of this kind of url :
myAppUrl/collections/units?collectionId=54
which can be done like this:
myStore.getProxy().extraParams.collectionId = 54;
I want to have a call like this:
myAppUrl/collections/54/units
My web service is adapted for both calls I just need the correct client code to pass the parameter.
Please help and advise.
An old question, but I write for anyone with this problem. I implemented the idea of #Saki in this package (for ExtJS 6) because of my own needs:
https://bitbucket.org/alfonsonishikawa/extjspackages/wiki/Server%20URL%20Placeholders
The idea is being able to use an URL like:
proxy: {
type: 'rest',
url: 'myAppUrl/collections/${collectionId}/units',
appendId: false
}
With that package, you just have to configure your proxy like above and call #load() with params:
store.load({
params: {
collectionId: 54
}
});
(getProxy().extraParams can be used as default value)
This is the source code as example that you asked #Saki about.
It looks almost like REST request but not exactly as REST places indexes at the end of url. You could solve it by implementing a custom buildUrl of Ajax or Rest proxy. In any case, see how is this method implemented in Rest proxy.
you can set your url dynamically and then call load method of store using below code.
store.getProxy().setUrl('your new url');
store.load();
but if you gonna use this method then you have to set correct url every time other-vice may be you will get wrong data.

URL of a collection in Backbone for RESTful interaction

Here is a collection I define in backbone.js
var List=Backbone.Collection.extend({
model: Item,
url: "TodoApp/index.php/todo"
});
var list=new List
Then I created a Model in the collection with an ID=80
Now, when I do list.fetch();
It will make a call to
"TodoApp/index.php/todo/80"
However, at the backend, using Codeigniter, I really need to have
TodoApp/index.php/todo/get/82.........where get is a function I defined to access DB
So, should I change the Collection url to "TodoApp/index.php/todo/get"
But again, that's not really where the resource is located?
In route.php try:
$route['todo/(:num)'] = "todo/get/$1";
HERE is what I ended up doing.
I renamed the index of the controller to resource
therefore using a URL of:
TodoApp/index.php/todo/resource
When getting a GET request at
TodoApp/index.php/todo/resource/80
extract the second segment of the URI and read from DB with that.

Categories