sending multiple array in multiple array in Angular js - angularjs

How to send this data in AngularJS. (It's a multiple array in a multiple array which need to send on one Object)
[{
"working_day":"sunday",
"from_time":{"hour":"9","min":"30"},
"to_time":{"hour":"6","min":"30"}
},{
"working_day":"monday",
"from_time":{"hour":"9","min":"30"},
"to_time":{"hour":"6","min":"30"}... and so on for other week days
}]
I am trying to send data like this in an API and I am new to AngularJs, so please tell me how can I make this data through HTML at runtime?
$scope.schedule = []; // Hard coded value
$scope.week = {};
$scope.week.working_day = "Sunday";
$scope.week.from_time = {};
$scope.week.from_time.min = "10:00";
$scope.week.from_time.max = "5:00";
$scope.week.to_time = {};
$scope.week.to_time.min = "2:10";
$scope.week.to_time.max = "8:00";
var dataParam = {
"prefix":$scope.data1.prefix,
"first_name":$scope.data1.first_name,
"password":$scope.data1.password,
"last_name":$scope.data1.last_name,
"email_id":$scope.data1.email_id,
"mobile_number":$scope.data1.mobile_number,
"roleCode":[$scope.data1.roleCode],
"role":[$scope.data1.role],
"Schedule":angular.toJson($scope.schedule.push($scope.week))
}
console.log(angular.toJson(dataParam));
/* $http({
url: "/here",
method: "POST",
headers :{'Content-Type': 'application/json','Accept': 'application/json' },
data: dataParam
}) .success(function(response) {
if(response.status_code=="success")
{
$scope.successmsg = response.status_message;
console.log(angular.toJson(response));
$state.go('dashboard.setting.user', {'user': $scope.viewUser});
}
else {
$scope.successmsg = response.status_code;
}
}); */
};
for now i just need to send this data format with angular js, please suggest
this is what i am doing in angular by "hard code" i need to send this data in angular js, how can i do that?
now please help me with html code of angular to send that hard coded value into runtime value by user

Have an array
$scope.schedule = [];
Create an object with your Json keys
$scope.week = {};
$scope.week.working_day = "";
$scope.week.from_time = {};
$scope.week.from_time.min = "";
$scope.week.from_time.max = "";
$scope.week.to_time = {};
$scope.week.to_time.min = "";
$scope.week.to_time.max = "";
Push it into array
$scope.schedule.push($scope.week);

Related

Convert Json string to object List in angular controller MVC web application

Guys I'm stuck with something. I have to convert a Json string to an object list.
I am working on a MVC project and I'm in the middle of an API integration.
Here's the data of the problem. I managed to get data list(has a tree structure) object from a cloud api and converted it to a Json string in MY WEBAPI.
This is the query
var textvar = (from avbH in avb_Hotels
join catRs in cat_Rs on avbH.categoryCode equals catRs.code
join rep in hotelRepList on avbH.code equals rep.code
select new
{
code= avbH.code,
destinationCode = avbH.destinationCode,
description = rep.description,
hotelstar = catRs.simpleCode,
checkIn = hotelBooking.DepartureDate,
checkOut = hotelBooking.ReturnDate,
name = avbH.name,
address = rep.address,
accommodationTypeCode = rep.accommodationTypeCode,
minRate = (int)Math.Round(Convert.ToDecimal(avbH.minRate) * rates),
images = "http://photos.hotelbeds.com/giata/" + rep.imagepath,
rooms = avbH.rooms,
ratecomment = avbH.ratecomment,
});
This is the converting part and I returned it as a string to the webUI.
result = JsonConvert.SerializeObject(textvar2, Newtonsoft.Json.Formatting.None);// then returns result
I need to convert this again to a object tree in the angular controller of my webUI.
I tried angular.fromJson but it doesn't work
app.service("APIService", function($http) {
this.hotelavailability = function(sub) {
return $http({
method: "post",
data: sub,
contentType: "application/json; charset=utf-8;text/plain",
timeout:30000,
url: "/api/HotelBooking/Availability"
});
}
app.controller("APIController", function ($scope, $window, $http, filterFilter, APIService, States) {
var getAll = "";
getAll = APIService.hotelavailability(sub);
getAll.then(function (d) { // d has the returning Json string
console.log("Succss");
$scope.hotels = angular.fromJson(d.data); //deserialization<-- This doesnt work
console.log($scope.hotels);
$scope.respData = angular.fromJson(d.data);
}
This is d(returning Json string from the webAPI)
getAll.then(function (d) { // d has the returning Json string
console.log("Succss");
$scope.hotels = angular.fromJson(d.data);
$scope.hotellist = angular.fromJson($scope.hotels);
}
I think this will work.

How to merge REST call results in Angular app more efficiently

I have an Angular SPA running on a SharePoint 2013 page. In the code, I'm using $q to pull data from 10 different SharePoint lists using REST and then merging them into one JSON object for use in a grid. The code runs and outputs the intended merged data but it's leaky and crashes the browser after a while.
Here's the code in the service:
factory.getGridInfo = function() {
var deferred = $q.defer();
var list_1a = CRUDFactory.getListItems("ListA", "column1,column2,column3");
var list_1b = CRUDFactory.getListItems("ListB", "column1,column2,column3");
var list_2a = CRUDFactory.getListItems("ListC", "column4");
var list_2b = CRUDFactory.getListItems("ListD", "column4");
var list_3a = CRUDFactory.getListItems("ListE", "column5");
var list_3b = CRUDFactory.getListItems("ListF", "column5");
var list_4a = CRUDFactory.getListItems("ListG", "column6");
var list_4b = CRUDFactory.getListItems("ListH", "column6");
var list_5a = CRUDFactory.getListItems("ListI", "column7");
var list_5b = CRUDFactory.getListItems("ListJ", "column7");
$q.all([list_1a, list_1b, list_2a, list_2b, list_3a, list_3b, list_4a, list_4b, list_5a, list_5b])
.then(function(results){
var results_1a = results[0].data.d.results;
var results_1b = results[1].data.d.results;
var results_2a = results[2].data.d.results;
var results_2b = results[3].data.d.results;
var results_3a = results[4].data.d.results;
var results_3b = results[5].data.d.results;
var results_4a = results[6].data.d.results;
var results_4b = results[7].data.d.results;
var results_5a = results[8].data.d.results;
var results_5b = results[9].data.d.results;
var combined_1 = results_1a.concat(results_1b);
var combined_2 = results_2a.concat(results_2b);
var combined_3 = results_3a.concat(results_3b);
var combined_4 = results_4a.concat(results_4b);
var combined_5 = results_5a.concat(results_5b);
for(var i = 0; i < combined_1.length; i++){
var currObj = combined_1[i];
currObj["column4"] = combined_2[i].column4;
currObj["column5"] = combined_3[i].column5;
currObj["column6"] = combined_4[i].column6;
currObj["column7"] = combined_5[i].column7;
factory.newObjectArray[i] = currObj;
}
deferred.resolve(factory.newObjectArray);
},
function (error) {
deferred.reject(error);
});
return deferred.promise;
};
Here's the REST call in CRUDFactory:
factory.getListItems = function (listName, columns){
var webUrl = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getByTitle('"+listName+"')/items?$select="+columns+"&$top=5000";
var options = {
headers: { "Accept": "application/json; odata=verbose" },
method: 'GET',
url: webUrl
};
return $http(options);
};
And then here's the controller bit:
$scope.refreshGridData = function(){
$scope.hideLoadingGif = false;
$scope.GridData = "";
GlobalFactory.getGridInfo()
.then(function(){
$scope.GridData = GlobalFactory.newObjectArray;
$scope.hideLoadingGif = true;
});
};
UPDATE 1: Per request, Here's the HTML (just a simple div that we're using angular-ui-grid on)
<div ui-grid="GridOptions" class="grid" ui-grid-selection ui-grid-exporter ui-grid-save-state></div>
This code starts by declaring some get calls and then uses $q.all to iterate over the calls and get the data. It then stores the results and merges them down to 5 total arrays. Then, because my list structure is proper and static, I'm able to iterate over one of the merged arrays and pull data from the other arrays into one master array that I'm assigning to factory.newObjectArray, which I'm declaring as a global in my service and using as my grid data source.
The code runs and doesn't kick any errors up but the issue is with (I believe) the "getGridInfo" function. If I don't comment out any of the REST calls, the browser uses 45 MB of data that doesn't get picked up by GC which is then compounded for each click until the session is ended or crashes. If I comment out all the calls but one, my page only uses 18.4 MB of memory, which is high but I can live with it.
So what's the deal? Do I need to destroy something somewhere? If so, what and how? Or does this relate back to the REST function I'm using?
UPDATE 2: The return result that the grid is using (the factory.newObjectArray) contains a total of 5,450 items and each item has about 80 properties after the merge. The code above is simplified and shows the pulling of a couple columns per list, but in actuality, I'm pulling 5-10 columns per list.
At the end of the day you are dealing with a lot of data, so memory problems are potentially always going to be an issue and you should probably consider whether you need to have all the data in memory.
The main goal you should probably be trying to achieve is limiting duplication of arrays, and trying to keep the memory footprint as low as possible, and freeing memory as fast as possible when you're done processing.
Please consider the following. You mention the actual number of columns being returned are more than your example so I have taken that into account.
factory.getGridInfo = function () {
var deferred = $q.defer(),
// list definitions
lists = [
{ name: 'ListA', columns: ['column1', 'column2', 'column3'] },
{ name: 'ListB', columns: ['column1', 'column2', 'column3'], combineWith: 'ListA' },
{ name: 'ListC', columns: ['column4'] },
{ name: 'ListD', columns: ['column4'], combineWith: 'ListC' },
{ name: 'ListE', columns: ['column5'] },
{ name: 'ListF', columns: ['column5'], combineWith: 'ListE' },
{ name: 'ListG', columns: ['column6'] },
{ name: 'ListH', columns: ['column6'], combineWith: 'ListG' },
{ name: 'ListI', columns: ['column7'] },
{ name: 'ListJ', columns: ['column7'], combineWith: 'ListI' },
],
// Combines two arrays without creating a new array, mindful of lenth limitations
combineArrays = function (a, b) {
var len = b.length;
for (var i = 0; i < len; i = i + 5000) {
a.unshift.apply(a, b.slice(i, i + 5000));
}
};
$q.all(lists.map(function (list) { return CRUDFactory.getListItems(list.name, list.columns.join()); }))
.then(function (results) {
var listResultMap = {}, var baseList = 'ListA';
// map our results to our list names
for(var i = 0; i < results.length; i++) {
listResultMap[lists[i].name] = results[i].data.d.results;
}
// loop around our lists
for(var i = 0; i < lists.length; i++) {
var listName = lists[i].name, combineWith = lists[i].combineWith;
if(combineWith) {
combineArrays(listResultMap[combineWith], listResultMap[listName]);
delete listResultMap[listName];
}
}
// build result
factory.newObjectArray = listResultMap[baseList].map(function(item) {
for(var i = 0; i < lists.length; i++) {
if(list.name !== baseList) {
for(var c = 0; c < lists[i].columns.length; c++) {
var columnName = lists[i].columns[c];
item[columnName] = listResultMap[list.name][columnName];
}
}
}
return item;
});
// clean up our remaining results
for (var i = 0; i < results.length; i++) {
delete results[i].data.d.results;
delete results[i];
}
deferred.resolve(factory.newObjectArray);
},
function (error) {
deferred.reject(error);
});
return deferred.promise;
};
I would suggest to add some sort of paging option... It's perhaps not a great idea to add all results to one big list.
Next i would suggest against ng-repeat or add a "track by" to the repeat function.
Check out: http://www.alexkras.com/11-tips-to-improve-angularjs-performance/
Fiddler your queries, the issue is probably rendering all the elements in the dom... Which could be kinda slow ( investigate)

Multiple Queries with Parse Cloud Code Using Promises

I have two questions:
Is the below example the right way to execute multiple Parse queries in a single Cloud Code function?
Is the below example going to provide all the data I'm querying with one HTTP request (when I call logbookEntries) and then count as two Parse requests on my account because it's two Parse queries?
Here's the code:
Parse.Cloud.define("logbookEntries", function(request, response) {
//::: Query 1 :::
var firstQuery = new Parse.Query("Logbook");
var returnData = [];
firstQuery.find().then(function(firstResults) {
returnData[0] = firstResults;
}).then(function(result) {
//::: Query 2 :::
var secondQuery = new Parse.Query("Logbook");
secondQuery.find().then(function(secondResults))
returnData[1] = secondResults;
}).then(function(result) {
response.success(returnData);
}, function(error) {
response.error(error);
});
});
Thanks in advance.
It's one way, though not quite correct.
Yes
Your code should really be:
Parse.Cloud.define("logbookEntries", function(request, response) {
//::: Query 1 :::
var firstQuery = new Parse.Query("Logbook");
var returnData = [];
firstQuery.find().then(function(firstResults) {
returnData[0] = firstResults;
var secondQuery = new Parse.Query("Logbook");
return secondQuery.find();
}).then(function(result) {
returnData[1] = result;
response.success(returnData);
}, function(error) {
response.error(error);
});
});
Or, a better way to structure it would be:
Parse.Cloud.define("logbookEntries", function(request, response) {
var firstQuery = new Parse.Query("Logbook");
var secondQuery = new Parse.Query("Logbook");
var promises = [];
promises.push(firstQuery.find());
promises.push(secondQuery.find());
Parse.Promise.when(promises).then(function(result1, result2) {
var returnData = [];
returnData[1] = result1;
returnData[2] = result2;
response.success(returnData);
}, function(error) {
response.error(error);
});
}
Just to update Wain's structured code:
Promise.when returns array when supplied with an array, so the correct code would be
Parse.Promise.when(promises).then(function([result1, result2]) {
and since there is no need to repack the array, it would simply be
Parse.Promise.when(promises).then(function(result) {
response.success(result);
See here for more info.

store data issue with generic grid rendered in tabs

I have a generic grid component.
on click of menu item corresponding grid is displayed in independent tabs.
on rendering the grid component, store data is set dynamically and grid is populated.
The problem if I open two grids in two tabs, on navigating to the first tab, grid data is not displayed as the store data is set to second grid data.
Hoping to find solution.Thank you
code in main controller:
OnMenuItemClick: function(c){
var nodeText = c.text,
tabs = Ext.getCmp('app-tab'),
tabBar = tabs.getTabBar(),
tabIndex;
for(var i = 0; i < tabBar.items.length; i++) {
if (tabBar.items.get(i).getText() === nodeText) {
tabIndex = i;
}
}
if (Ext.isEmpty(tabIndex)) {
/* Note: While creating the Grid Panel,here we are passing the Menu/Grid Id along with it for future reference */
tabs.add(Ext.create('DemoApp.view.grid.GenericGrid',{title:nodeText,gridId:c.id,overflowY: 'scroll',closable:true}));
tabIndex = tabBar.items.length - 1 ;
}
tabs.setActiveTab(tabIndex);
}
code in generic grid controller:
renderGridMetadata: function(genericGrid) {
var store = Ext.getStore("DemoApp.store.GenericGrid"),
gridId = genericGrid.up().gridId,
resourceURL = "resources/data/" + gridId + ".json";
var serviceInput = Util.createServiceResponse(gridId);
/*Dynamically add the proxy URL to the ViewModel
DemoApp.model.GenericGrid.getProxy().setUrl(resourceURL);*/
Ext.getBody().mask("Loading... Please wait...", 'loading');
Ext.Ajax.request({
url: Util.localGridService,
method: 'POST',
headers: {
"Content-Type": "application/json",
'SM_USER': 'arun.x.kumar.ap#nielsen.com',
'SM_SERVERSESSIONID': 'asdfadsf'
},
jsonData: {
getConfigurationAndDataRequestType: serviceInput
},
success: function(conn, response, options, eOpts) {
Ext.getBody().unmask();
var data = Util.decodeJSON(conn.responseText);
/* Apply REST WebServices response Metadata to the Grid */
var recordsMetaData = data.getConfigurationAndDataReplyType.gridConfigDataResponse.data.record;
var jsonMetaDataArray = [];
for (var c = 0; c < recordsMetaData.length; c++) {
var jsonMetaDataObject = {};
var text = data.getConfigurationAndDataReplyType.gridConfigDataResponse.data.record[c].displayName;
var dataIndex = data.getConfigurationAndDataReplyType.gridConfigDataResponse.data.record[c].columnName;
jsonMetaDataObject["text"] = text;
jsonMetaDataObject["dataIndex"] = dataIndex;
jsonMetaDataArray.push(jsonMetaDataObject);
}
/* Apply REST WebServices response data to the Grid */
var recordsData = data.getConfigurationAndDataReplyType.gridDataResponse.record;
var jsonDataArray = [];
for (var r = 0; r < recordsData.length; r++) {
var columnsData = data.getConfigurationAndDataReplyType.gridDataResponse.record[r].column;
var jsonDataObject = {};
for (var c = 0; c < columnsData.length; c++) {
jsonDataObject[columnsData[c].columnId] = columnsData[c].columnValue;
}
jsonDataArray.push(jsonDataObject);
}
store.setData(jsonDataArray);
genericGrid.reconfigure(store, jsonMetaDataArray);
},
failure: function(conn, response, options, eOpts) {
Ext.getBody().unmask();
Util.showErrorMsg(conn.responseText);
}
});
store.load();
}
});
Most likely there is only one instance of DemoApp.store.GenericGrid.
Frankly, I only guess because I see that you call Ext.getStore("DemoApp.store.GenericGrid") that implies the store is declared in stores:["DemoApp.store.GenericGrid"] array probably in the application class.
If a store is declared this way then Ext automatically creates one instance of it setting storeId to the string listed in stores:[]. Hence, Ext.getStore() returns that instance.
If you want to have two independent instances of the grid you have to create store instances yourself preferably in initComponent override.

Built a JSON from string pieces

I work with a line chart in ExtJS4 now. The chart is based on the data of the store. The store change its data with help 'loadRawData()' function.
Familiar situation, isn't it?
AJAX sends strings every 10 seconds and I need to built JSON from this pieces of strings. I'm trying:
success: function(response) {
var requestMassive = JSON.parse(response.responseText);
var jArray = [];
for(var i=0;i<requestMassive.length;i++){
var firstPiece = JSON.parse(response.responseText)[i].date;
var secondPiece = JSON.parse(response.responseText)[i].connectCount;
var recording = "{'machinesPlayed':"+firstPiece+", 'machinesOnline':"+secondPiece+"}";
jArray.push(recording);
}
jArray = '['+jArray+']';
store.loadRawData(jArray);
}
But it is wrong way. How to do it properly?
You could use loadData() function instead of loadRawData(). loadData() only needs an array of objects.
success: function(response) {
var requestMassive = JSON.parse(response.responseText);
var jArray = [];
for(var i=0;i<requestMassive.length;i++){
jArray.push({ machinesPlayed: requestMassive[i].date, machinesOnline: requestMassive[i].connectCount});
}
store.loadData(jArray);
}
I didnt get what you are trying to achieve.But it can be formed this way.Try this out.
var recording = {
"machinesPlayed" : firstPiece,
"machinesOnline" : secondPiece
}
jArray.push(recording);
OR
jArray.push({
"machinesPlayed" : firstPiece,
"machinesOnline" : secondPiece
});

Resources