Angular $http.query use array as params? - javascript

I have an Angular 1 application where a user can select several items by clicking on a checkbox. When he clicks a particular button, these Ids are aggregated as this:
angular.forEach($scope.orders, function (order, id) {
if (order.export) {
ids.push(order.id);
}
});
Now I want to query these Ids in my php api action, but how can I transmit all id's to my apiAction? I tried it with $http.query ($scope.items = Items.query({ 'ids' : ids});), but this does not work as it creates a strange url which can not be parsed.
Then I tried it with: $http.save and there I can transfer the ids to my api action, but I also need to return the result back to my application in order to show it on the frontend, but with using $http.save this does not seem to be possible, as I always get a orderBy:notarray error.
So how can I use $http.save and get a proper array in return or use $http.query with an array with multiple ids in the params?
Thanks

In angular $http call...
params: {
id: JSON.stringify(ids)
}

You can convert your array into comma separated string and then pass that string into your php api and then you can get back your array in php. E.g.,
Angular side,
ids.toString()
PHP side,
explode(",",$query_param);

Related

How to sort the relations returned using get work items API?

I am writing a TFS extension in javascript where I am using the 'GetWorkItem' function within 'TFS/WorkItemTracking/RestClient' library.
wiRestClient.getWorkItem(<workItemID>, null, null, Contracts.WorkItemExpand.All)
.then(function success(workItem) {
console.log(workItem);
});
the output generated by the code above is as below:
This PBI has about 40 tasks within it and they are fetched in random order by the API.
Is there a way that these relations are fetched in the order of their Id?
I process the relations returned in the result, fetch the Id from a forward relation, get the workItemId
and add it to an array.
Now, this array has information about all the child workitems of the parent PBI.
I tried to sort this array based on System.Id in the fields property.
This is the function I use to sort the data:
childWorkItems.sort(function(a,b) {
return a["System.Id"] > b.["System.Id"]
});
console.log(childWorkItems);
This doesn't seem to work. The array is still in random order.
I solved by changing the sort function to
childWorkItems.sort(function(a,b) {
return a["System.Id"] - b.["System.Id"]
});
console.log(childWorkItems);

How to save results from dynamic cascading drop down list?

I have 2 cascading drop down list , when page loads, data is loaded to the 1st DDL, when item is selected from this list its goes to the database and fetch matching items and populate 2nd DDL. I want to prevent going twice to the DB on selection.
For example, I am loading 1st DDL with cars manufactures then click on Toyota what happens next is it goes to DB and fetches all Toyota's models and populates the 2nd DDL, after that i select different car manufacture, same thing happens. Now when i select again Toyota from the 1st list it will not go to DB, it will pull the data from previous request.
I will like to keep an object (like dictionary) of the requests, so if item is already been requested it will not go back to the DB but use local saved data.
You can store list return from server through LocalStorage in Javascript. By using setItem()function as shown below.
window.localStorage.setItem('Toyota', 'Models');
Where Toyota is the key and Models is the value. Also note that LocalStorage can only store strings.
To store arrays or objects you would have to convert them to strings.
To do this we use the JSON.stringify() method before passing to setItem() .
const models = {
1: "Model-1",
2: "Model-2",
}
window.localStorage.setItem('Toyota', JSON.stringify(models));
Now when ever you select different car manufacture check its value in LocalStorage object first.
It accepts only one parameter which is the key and returns the value as a string.
To retrieve the Toyota key stored above:
window.localStorage.getItem('Toyota');
This returns a string with value as.
“{“1”:”Model-1”,”2”:”Model-2”}”
To use this value, you would have convert it back to an object.
To do this, we make use of JSON.parse() method which converts a JSON string into a Javascript Object.
JSON.parse(window.localStorage.getItem('Toyota'));
Please keep in mind to check weather your browser support Local storage or not.
if (typeof(Storage) !== "undefined") {
// Code for localStorage
} else {
// No web storage Support.
}
You can use Map() object to store the data based on key.
Find more information: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map
var brandModelsList = new Map();
function getBrandModels(brand)
{
if(brandModelsList.has(brand))
{
modelList = JSON.parse(brandModelsList.get(brand));
// Do stuff with second dropdown
}
//Your ajax stuff to get data
$.ajax({
url: 'server url',
data: {name: brand},
dataType: 'json',
}).done(response => {
brandModelsList.set(brand, JSON.stringify(response));
// Do stuff with second dropdown
});
}
It has support in most of modern browsers. A best tutorial on this is https://javascript.info/map-set-weakmap-weakset.
you can do this via JavaScript as #Rahat Hameed stated if the cascading dropdown values are not changed frequently, if they can be changed e.g (you can updated them via some logic).Then preferable ways it to fetch them from database.

How do you merge two jquery posts into one in coffeescript?

I need to merge these two objects:
{ swim_lane_id: $(this).closest('ul').data('lane-id') }
+
$(this).sortable('serialize')
into one object that can be sent as the [DATA] in a $.post:
$.post($(this).data('update-url'), [DATA] );
$.merge only gives swim_lane_id and an id that is part of the update-url data tag but doesn't give the serialized data from the sortable list.
I basically need to be able to pass these through in one post because the update-url data tag routes to a controller action in my Rails application and I need to know which list is being updated for every update action sent to it.
Well that looks simple enough :
$.post $(this).data('update-url'),
swim_lane_id : $(this).closest('ul').data('lane-id')
some_other_name : $(this).sortable('serialize')
You're passing the two properties in one object.

Breeze EntityManager.executeQuery with expand - httpResponse data does not match result data?

I'm working on a web app that uses Breeze and Knockout. I have the following function:
function getArticle(id, articleObservable) {
var query = EntityQuery.from('KbArticles')
.where("articleId", "==", id)
.expand("KbArticleType, KbSubject, KbArticleTags");
return manager.executeQuery(query)
.then(querySucceeded)
.fail(queryFailed);
function querySucceeded(data) {
if (articleObservable) {
articleObservable(data.results[0]);
}
log('Retrieved [Article] from remote data source', data.results.length, true);
}
}
A 1 to many relationship exists between the KbArticles entity and the KbArticleTags entity. The goal of this function is to fetch a specific article and the list of tags associated with the article. The function executes successfully (and I DO get data for the other 2 expanded entities - they are 1 to 1), however, I get an empty array for the KbArticleTags in data.results. Interestingly, the tags are populated in data.httpResponse:
So, it appears that the data is coming over the wire, but it's not making it to the results in the querySucceeded function. I tried to step through the breeze code to determine how the httpResponse is mapped to the result, but got lost fairly quickly (I'm a javascript newb). Does anyone have any troubleshooting tips for figuring out why the expanded entity doesn't show in the results, but is returned in the httpResponse? Or am I trying to do something that isn't supported?
Ok, so for whatever reason (I probably deleted it one day while testing and didn't add it back), the navigation property (in my Entity Framework diagram) was missing on the KbArticleTag entity:
All I had to do was add that back and everything is working as expected.

Fetch Backbone Collection by Model IDs list

I have a REST API serving a few URLs:
/rest/messages
provides all messages. A message is a JSON/Backbone Model
{
title: 'foo',
body : 'bar'
}
To get a single message I have:
/rest/messages/:id
Is it possible to fetch a Backbone Collection using message IDs array? I don't want the whole message list, but just a few messages I specify by ID.
I could fetch Models one-by-one and fill up the Collection, but I'm wondering if Backbone has a cleaner way to do this.
Thanks
According to documentation, you can pass ajax options to the fetch call. So, you can pass ids as data attribute to the fetch call being done and based on it, return the respective models from the server.
For example (when doing fetch),
collection.fetch({
data : {
message_ids : [1, 3, 5] // array of the message ids you want to retrieve as models
}
})
This message_id array will be accessible as parameters (not sure of the name in your case) in the server code being executed at /rest/messages, from there you can return only specific models based on ids you receive as message_ids. The only thing you need is, client side must be aware of the ids of all the message models it needs.
You can use any data structure instead of array to send message_ids.
The url property of collection reference to the collection location on the server. When you use fetch, backbone uses that url.
The url property can be also a function that returns the url. So you can do something like that:
var ids = [1,2,3]
var messages = new MessegecCollection();
messages.url = function() {
return "/rest/messages/"+ids.join("-"); //results "/rest/messages/1-2-3"
}
messages.fetch();
You can also create a method in your collection that generated and set the url, or even fetchs a set of models.
Now all you have to do is to support this url: /rest/messages/1-2-3
Hope this helps!

Categories

Resources