user6440175 user6440175 - 3 months ago 19
AngularJS Question

Pass the size of a data set to an angular service

Pass the size of the data set to angular service. I am trying to pass the size of the data set(count) to the angular service. I just started to work with angular and any help is greatly appreciated.

Controler:

public JsonResult GetAllCurrentSettings()
{
var jsonString = string.Empty;

string query = "SELECT * from test";

try
{
using (SqlConnection conn = new SqlConnection(connStringApps))
{
conn.Open();
using (SqlCommand command = new SqlCommand(query, conn))
{
DataTable dt = new DataTable();

using (SqlDataReader rdr = command.ExecuteReader())
{
dt.Load(rdr);
}

jsonString = Newtonsoft.Json.JsonConvert.SerializeObject(dt, Formatting.None);
return Json(jsonString);
}
}
}
catch (Exception ex)
{
Console.Write(ex.ToString());
return Json(jsonString);
}
}


Angular Service

myApp.service('allCurrentSettingsService', ['$http', '$q', function ($http, $q) {
var allSettings = null;
this.getList = function () {
var def = $q.defer()
if (allSettings) {
def.resolve(allSettings);
} else {
$http.post('GetAllCurrentSettings')
.then(function (response) {
var response = $.parseJSON(response.data)
allSettings = response;
def.resolve(allSettings);
});
}
return def.promise;
}
}]);

Answer
$http.post('GetAllCurrentSettings')
              .then(function (response) {
                  var response = $.parseJSON(response.data)

The response is already a JSON object.

$.parseJSON : Takes a well-formed JSON string and returns the resulting JavaScript value.

You can directly use response object like this:

def.resolve(response);