POSTing and PUTing a restangular object - angularjs

I am trying to create a new restangular object, POST it, modify it and then PUT it.
$scope.new_message = Restangular.one('messages');
// This should post
$scope.new_message.save().then(function(message){
$scope.new_message = message;
});
// This should PUT
$scope.new_message.subject = "Hello world";
$scope.new_message.save()
Unfortunately restangular is sending a PUT request to http:/localhost/messages/undefined/5481ebbfe252e4116a8334d0
When it should be
http://10.211.55.3/messages/5481ebbfe252e4116a8334d0
It seems that to use .one() you must include an id as one of the parameters. My question is, how I can leverage the .save() functionality without using an id

Related

Postman - How do I loop a request in another request's test script?

I have a request that returns an array and I, thanks to StackOverflow, figured out how to make each object in the array its own environment variable. Now I want to make a request per variable in the same request as I instantiated the variable. Here is what I got:
var a = pm.response.json();
for (i = 0;i < a.sick_beats.length; i++){
pm.environment.unset("Beat_" + (i+1));
pm.environment.set("Beat_" + (i+1), a.sick_beats[i]);
pm.sendRequest("Publish Beat");
}
It sends the request "Publish Beat" but uses it as the URL instead of referencing the request.
I guess my question is how can I reference a request name instead of a URL, since the old way postman.setNextRequest("Request_Name"); doesn't work.
This pm.* function doesn't work in this way:
pm.sendRequest("Publish Beat")
Check out this blog from Postman explaining it more.
This is a basic extract from the snippets in the application. The first arg is the URL.
pm.sendRequest("https://postman-echo.com/get", function (err, response) {
console.log(response.json());
});
You can use pm.setNextRequest('request_name') to create a workflow but this will only work in the Collection Runner and not for single requests. You can add a collection of requests and chain these together using the {{Beat_1}} variable in the URL.
Alternatively, you could add something like this but it's very hacky and wouldn't ever send requests over and over again, like the collection runner would:
var some_value = pm.environment.get('Beat_whatever')
pm.sendRequest(`https://your-super-secret-site.com/${some_value}`, (err, response) => {
// This is just here so you can see the response
console.log(response.json())
})

Issues with single-requests in Restangular

I'm having a slight issue with my ability to consume REST data retrieved via Restangular in an angular controller. I have the following code which works fine for a list of accounts:
var baseAccounts = Restangular.all('accounts');
baseAccounts.getList().then(function(accounts) {
$scope.accounts = accounts;
});
This works perfectly for a list. I use similar syntax for a single account:
var baseAccount = Restangular.one('accounts');
baseAccount.getList(GUID).then(function(returnedAccount) {
$scope.currentAccount = returnedAccount;
});
I am using ng-repeat as the handling directive for my first request. I am attempting to bind with {{ account.name }} tags for the single request, but it does not seem to display any data despite the request being made properly. GUID is the parameter I must pass in to retrieve the relevant record.
I have combed through Restangular docs and it seems to me like I am composing my request properly. Any insight would be greatly appreciated.
EDIT: I've tried all of the solutions listed here to no avail. It would seem Restangular is submitting the correctly structured request, but when it returns it through my controller it shows up as just a request for a list of accounts. When the response is logged, it shows the same response as would be expected for a list of accounts. I do not believe this is a scoping issue as I have encapsulated my request in a way that should work to mitigate that. So, there seems to be a disconnect between Request -> Restangular object/promise that populates the request -> data-binding to the request. Restangular alternates between returning the array of accounts or undefined.
Have you looked at:
https://github.com/mgonto/restangular#using-values-directly-in-templates
Since Angular 1.2, Promise unwrapping in templates has been disabled by default and will be deprecated soon.
Try:
$scope.accounts = baseAccounts.getList().$object;
try:
var baseAccount = Restangular.one('accounts', GUID);
baseAccount.get().then(function(returnedAccount) {
$scope.currentAccount = returnedAccount;
});
The problem here is that it's expecting an array to be returned. I'm assuming that you are expecting an account object. Thus we need to use the get function, intead of getList()
The one() function has a second argument that accepts an id e.g. .one('users', 1). You can take a use of it.
CODE
var baseAccount = Restangular.one('accounts', 1); //1 would be account id
baseAccount.getList('account').then(function(returnedAccount) {
$scope.currentAccount = returnedAccount;
});
OR
var baseAccount = Restangular.one('accounts', 1); //1 would be account id
baseAccount.all('account').getList().then(function(returnedAccount) {
$scope.currentAccount = returnedAccount;
});
For more info take look at github issue
Hope this could help you, Thanks.

laravel angularjs update multiple rows

i have a sortable table and after successfully moving an item i want to update all the rows in the databasetable which are effected from sorting.
my problem is that i dont know what's the best way to update multiple rows in my database with eloquent and how to send the data correct with angularjs
in angularjs i did this
//creating the array which i want to send to the server
var update = [];
for (min; min <= max; min++){
...
var item = {"id": id, "position": position};
update.push(item);
...
}
//it doesn't work because its now a string ...
var promise = $http.put("/api/album/category/"+update);
//yeah i can read update in my controller in laraval, but i need the fakeid, because without
//i get an error back from laravel...
var promise = $http.put("/api/album/category/fakeid", update);
in laravel i have this, but is there an possibility to update the table with one call instead of looping
//my route
Route::resource('/api/album/category','CategoryController');
//controller
class CategoryController extends BaseController {
public function update()
{
$updates = Input::all();
for($i = 0; $i<count($updates); $i++){
Category::where('id','=', $updates[$i]["id"])
->update(array('position' => $updates[$i]["position"]));
}
}
}
and yes this works but i think there are better ways to solve the put request with the fakeid and the loop in my controller ;)
update
k routing is solved ;) i just added an extra route
//angularjs
var promise = $http.put("/api/album/category/positionUpdate", update);
//laravel
Route::put('/api/album/category/positionUpdate','CategoryController#positionUpdate');
Try post instead put.
var promise = $http.post("/api/album/category/fakeid", update);
PUT vs POST in REST
PUT implies putting a resource - completely replacing whatever is available at the given URL with a different thing. By definition, a PUT is idempotent. Do it as many times as you like, and the result is the same. x=5 is idempotent. You can PUT a resource whether it previously exists, or not (eg, to Create, or to Update)!
POST updates a resource, adds a subsidiary resource, or causes a change. A POST is not idempotent, in the way that x++ is not idempotent.
By this argument, PUT is for creating when you know the URL of the thing you will create. POST can be used to create when you know the URL of the "factory" or manager for the category of things you want to create.
so:
POST /expense-report
or:
PUT /expense-report/10929
I learned via using following
Laravel+Angular+Bootstrap https://github.com/silverbux/laravel-angular-admin
Laravel+Angular+Material https://github.com/jadjoubran/laravel5-angular-material-starter
Hope this help you understand how to utilize bootstrap & angular and speed up your develop by using starter. You will be able to understand how to pass API request to laravel and get callback response.

Restangular data sent is being splitted

Restangular.one('suppliers', 'me').getList('websites').then(
(data) ->
$scope.websites = data
$scope.websites.patch()
)
I'm just trying this for a quick test.
So the api call on /suppliers/me/websites returns an array but when I try to patch from the Restangular object it sends the data splitted as you can see below.
[{"0":"h","1":"t","2":"t","3":"p","4":":","5":"/","6":"/","7":"w","8":"w","9":"w","10":".","11":"p","12":"f","13":"c","14":"o","15":"n","16":"c","17":"e","18":"p","19":"t","20":".","21":"c","22":"o","23":"m"}]
I'm new to Angular & Restangular , what am I missing ?
Edit : To be clear, I insta patch for the test but normally I modify the websites array by adding / removing.
It looks as if you're returning a string from your service, whereas a valid JSON response is expected by Restangular.
For example:
[{"website": "http://www.example.com"}, {"website": "http://www.domain.com"}]
EDIT: I just noticed that in your question, you say your service returns an array. Double-check what it does return and make sure that it is valid JSON.
EDIT 2: It seems that Restangular expects not only valid JSON, but also JSON formatted as my code sample above is (ie. [{"key": "value"}] and not ["value"].

Restangular POST data not being read by Django

I've done a lot of searching and nothing seems to fully address this. I've created a REST API that has a resource to send a message. The path is /api/v1/conversation/{type}/{id}/message. Placing a POST call to that URI will create a message for the given conversation.
Everything works great if I just use $.post('/api/v1/conversation/sample/sample/message', {message: "All your base are belong to us"});
However, I'd like to use Restangular, and for some reason, it is sending the POST data in a way that I have to work with request.body instead of request.POST.get('message'). This is terribly inconvenient if I have to do this with every single server side API.
Here's my Restangular code:
conversation = Restangular.one('conversation', scope.type).one(scope.type_id);
conversation.post('message', {message: "All your base..."})
To clarify, it is POSTing to the correct URI, it just is sending the post data as a payload instead of as form data. How can I configure it to send the post as form data?
Edit:
As a side note, I was able to mitigate this issue by creating a utility function:
def api_fetch_post(request):
post = request.POST
if not post:
try:
post = json.loads(request.body.decode(encoding='UTF-8'))
except:
pass
return post
This way I can accept either type of POST data. Regardless, is there a way to send form data with Restangular?
Yes, there is.
var formData = new FormData();
formData.append('message', $scope.message);
// Or use the form element and have formData = new FormData(formElement).
Restangular.one('conversation', $scope.type).one($scope.type_id)
.withHttpConfig({transformRequest: angular.identity})
.post(formData, null, {'Content-Type': undefined})
.then(function(response){
// Do something with response.
});

Resources