I have following function which worked fine until i tried to call another assync request from this assync function. If i tried it secondary assync function always returns exception.
"Has bo method 'then'"
Has anybody idea what can causing it and how can i solve it plese?
Thanks for any help.
First assync function
$scope.getData = function() {
var deferred = $q.defer();
var DATE_FROM = dateFrom;
var DATE_TO = dateTo;
// INSTANTIATE DB CONNECTION
db = window.sqlitePlugin.openDatabase({name:"callplanner"});
var numberOfProcessed = 0;
for(var ic=0; ic < dateRanges.length; ic++) {
var sqlQuery =
"SELECT '"+dateRanges[ic].DATE_FROM+"' as DATE_FROM, "+
" '"+dateRanges[ic].DATE_TO+"' as DATE_TO, "+
" COUNT(*) AS DIALS_CNT, "+
" SUM(CASE WHEN dc.call_result = '"+CALL_RESULT_STATE_APPT+"' THEN 1 ELSE 0 END) AS '"+APPT_CNT+"', "+
" SUM(CASE WHEN dc.call_result = '"+CALL_RESULT_STATE_CONV_NO_APPT+"' THEN 1 ELSE 0 END) AS '"+CONVERS_CNT+"' , "+
" SUM(CASE WHEN dc.call_result = '"+CALL_RESULT_STATE_CANNOT_REACH+"' THEN 1 ELSE 0 END) AS '"+CANNOT_REACH_CNT+"' "+
" FROM "+DIALED_CALLS_TABLE+" dc "+
" WHERE dc.date BETWEEN '"+dateRanges[ic].DATE_FROM+"' AND '"+dateRanges[ic].DATE_TO+"';";
// PRINT QUERY
console.log(sqlQuery);
// PUSH QUERY TO ARRAY
sqlQueries.push(sqlQuery);
// PROCESS TRANSACTION
db.transaction(function(tx) {
// init empty array for results
tx.executeSql(sqlQueries[numberOfProcessed], [], function(tx,results){
for (var i=0; i < results.rows.length; i++){
//process your result from sql
numberOfProcessed++;
row = results.rows.item(i);
// Replace null values
if(row.APPT_CNT == null)
row.APPT_CNT = 0;
if(row.CONVERS_CNT == null)
row.CONVERS_CNT = 0;
if(row.CANNOT_REACH_CNT == null)
row.CANNOT_REACH_CNT = 0;
// End of replacing null values
row.YOUR_GOAL = $rootScope.goalValue;
row.YOUR_DEFICIT = DialsComputeService.computeDailyDeficit(row);
row.SUCCESS_RATE = DialsComputeService.computeSuccessRateDaily(row);
//row.SUCCESS_RATE_SINCE = DialsComputeService.computeSuccessRateSinceStart(row);
// GET DATA IN ASSYNC TASK
DialsComputeService.computeSuccessRateSinceStart.then(function(result){
// THIS GIVES THE VALUE:
//alert("Result is" + JSON.stringify(result));
console.log("Returned Result is: " + JSON.stringify(result));
try{
row.SUCCESS_RATE_SINCE = result;
} catch (e) {
$ionicLoading.show({
template: $translate.instant('ERROR'),
duration:1000
});
}
}, function(e){
$ionicLoading.show({
template: $translate.instant('ERROR_DATABASE'),
duration:1000
});
});
// END GET DATA IN ASSYNC TASK
statsData.push(row);
console.log("Result row is: " + JSON.stringify(row));
if(numberOfProcessed == dateRanges.length){
deferred.resolve(statsData); // resolve your promise when you are sure you handled everything
}
}
});
},function (e) {
alert("ERROR: " + e.message);
deferred.reject(e);
});
}
return deferred.promise;
};
Second assync function in service:
computeSuccessRateSinceStart: function(row) {
var deferred = $q.defer();
console.log("Trying to compute daily success rate since until" +row.DATE_TO);
var sqlQuery =
"SELECT " +
"("+
"SELECT COUNT(*) "+
"FROM dialed_calls AS dc "+
"WHERE dc.date < '"+row.DATE_TO+"'" +
") " +
"AS DIALS_CNT ," +
"("+
"SELECT COUNT(dc.call_result) "+
"FROM dialed_calls AS dc "+
"WHERE dc.call_result = 'APPT_CNT' "+
"AND "+
"dc.date < '"+row.DATE_TO+"'" +
") " +
"AS APPT_CNT ;";
console.log(sqlQuery);
db = window.sqlitePlugin.openDatabase({name:"callplanner"});
// GET APPT COUNT
db.transaction(function(tx) {
tx.executeSql(sqlQuery, [], function(tx,results){
// init empty array for results
for (var i=0; i < results.rows.length; i++){
row = results.rows.item(i);
//Udpate date for writeout
//row.DATE = moment(row.DATE).format('ddd DD.M');
console.log("row APPT count is " + JSON.stringify(row));
alert(JSON.stringify(row));
var successRateFromSince;
successRateFromSince = row.APPT_CNT / row.DIALS_CNT * (100);
successRateFromSince = Math.round(successRateFromSince);
if(isNaN(successRateFromSince)) {
successRateFromSince = 0;
}
console.log("Success rate since is " +successRateFromSince);
}
deferred.resolve(successRateFromSince);
});
},function (e) {
alert("ERROR: " + e.message);
$ionicLoading.show({
template: $translate.instant('ERROR_DATABASE'),
duration:1000
});
});
return deferred.promise;
}
};
Place where error is occured:
// GET DATA IN ASSYNC TASK
DialsComputeService.computeSuccessRateSinceStart.then(function(result){
// THIS GIVES THE VALUE:
//alert("Result is" + JSON.stringify(result));
console.log("Returned Result is: " + JSON.stringify(result));
try{
row.SUCCESS_RATE_SINCE = result;
} catch (e) {
$ionicLoading.show({
template: $translate.instant('ERROR'),
duration:1000
});
}
}, function(e){
$ionicLoading.show({
template: $translate.instant('ERROR_DATABASE'),
duration:1000
});
});
// END GET DATA IN ASSYNC TASK
Your async function computeSuccessRateSinceStart is a function, so you need to call it as a function and pass it a row as a parameter:
DialsComputeService.computeSuccessRateSinceStart(yourRow).then( ... )
Once you do that, the return value from the function will be a promise, which has a then() method.
Related
I am trying to insert the sensor data into a SQL Server database. I have tried all the possible way to insert the incoming data into database, but I failed. I am new to Nodejs and I really have no idea why these errors are occurred during executing process. It would be great if anyone could help me.
Thank you in advance.
The error I get is:
TypeError: Cannot read property 'writeHead' of undefined.
function addData (req, resp, reqBody, data)
{
try {
if (!reqBody) throw new Error("Input not valid");
data = JSON.parse(reqBody);
//reqBody = JSON.parse(data);
if (data) {//add more validations if necessary
var sql = "INSERT INTO arduinoData (Machine, StartTime, EndTime, LengthTime) VALUES ";
sql += util.format("(%s, '%s', %s, %s) ", data.Machine, data.StartTime, data.EndTime, data.LengthTime);
db.executeSql(sql, function (data, err) {
if (err) {
httpMsgs.show500(req, resp, err);
}
else {
httpMsgs.send200(req, resp);
}
});
}
else {
throw new Error("Input not valid");
}
}
catch (ex) {
httpMsgs.show500(req, resp, ex);
}
};
function sendBackupData()
{
var jsonTable = { "table": [] };
fs.readFile("backup.json", "utf8", function (err, data) {
if (err) throw err;
jsonTable = JSON.parse(data);
if (jsonTable.table.length == 0) {
return;
}
for (var index = 0; index < jsonTable.table.length; index++) {
var options = {
url: serverURL,
method: "POST",
form: jsonTable.table.shift()
};
request.post(options, function (error, response, body) {
if (!error) {
console.log("Sent backup message!");
} else {
console.log('Error: ' + error);
console.log("CANT'T SEND BACK");
console.log(options.form);
jsonTable.table.push(options.form);
}
});
}
var outputJSON = JSON.stringify(jsonTable);
console.log(outputJSON);
fs.writeFile("backup.json", outputJSON, "utf8", function (err) {
if (err) throw err;
console.log("Sent backup data!");
});
});
}
function getTime()
{
var date = new Date();
var year = date.getFullYear();
var month = ('0' + (date.getMonth() + 1)).slice(-2);
var day = ('0' + date.getDate()).slice(-2);
var hour = ('0' + date.getHours()).slice(-2);
var minute = ('0' + date.getMinutes()).slice(-2);
var second = ('0' + date.getSeconds()).slice(-2);
// Unix Time
var unixTime = Math.floor(date / 1000);
// Check if it is day or night
var isDay;
if (date.getHours() >= 8 & date.getHours() < 16)
{
isDay = true;
}
else
{
isDay = false;
}
return [year + '-' + month + '-' + day, hour + ':' + minute + ':' + second, unixTime, isDay];
}
/*
--- Main Code ---
*/
function vibrationStart()
{
/*
Should get:
- Start time and date the vibration started
- Whether it was day or night
Will send the message, if there is network connection, once complete.
Will store message into a JSON file if there is no network connection.
*/
var jsonTable = { "table": [] };
var startTime = getTime();
console.log(startTime[0] + " " + startTime[1]);
var startData = {
machine: machineName,
start_time: startTime[0] + " " + startTime[1],
day_night: startTime[3],
active: "true"
};
const options = {
url: serverURL,
method: "POST",
form: startData
};
var reqBody = [{
Machine : "",
StartTime : ""
}];
reqBody.push({"Machine" : startData.machine,"StartTime" : startData.start_time});
var outputJSON = JSON.stringify(reqBody);
request.post(options, function (error, response, body) {
if (!error) {
console.log("Sent starting message!");
sendBackupData();
addData();
} else {
console.log("CANT'T SEND");
// Write to JSON file for backup if can't send to server
fs.readFile("backup.json", "utf8", function readFileCallback(err, data) {
if (err) throw err;
jsonTable = JSON.parse(data);
jsonTable.table.push(startData);
var outputJSON = JSON.stringify(jsonTable);
fs.writeFile("backup.json", outputJSON, "utf8", function (err) {
if (err) throw err;
});
});
}
});
return startTime[2];
}
function vibrationStop(startTimeUnix)
{
var jsonTable = { "table": [] };
var endTime = getTime();
console.log(endTime[0] + " " + endTime[1]);
var endTimeUnix = endTime[2];
var lengthTime = endTimeUnix - startTimeUnix;
console.log("Length time: " + lengthTime);
var endData = {
machine: machineName,
end_time: endTime[0] + " " + endTime[1],
length_time: lengthTime,
active: "false"
};
const options = {
url: serverURL,
method: "POST",
form: endData
};
var reqBody = [{
EndTime : "",
LengthTime :"",
}];
reqBody.push({"EndTime" : endData.end_time,"LengthTime" : endData.length_time});
var outputJSON = JSON.stringify(reqBody);
request.post(options, function (error, response, body) {
if (!error) {
console.log("Sent end message!");
sendBackupData();
addData()
} else {
console.log("CANT'T SEND");
// Write to JSON file for backup if can't send to server
fs.readFile("backup.json", "utf8", function readFileCallback(err, data) {
if (err) throw err;
jsonTable = JSON.parse(data);
jsonTable.table.push(endData);
var outputJSON = JSON.stringify(jsonTable);
fs.writeFile("backup.json", outputJSON, "utf8", function (err) {
if (err) throw err;
});
});
}
});
}
http.createServer(function (req, resp) {
app.get('/', addData);
}).listen(settings.webPort, function () {
console.log("Started listening at: " + settings.webPort);
});
I have an AngularJS/MVC application that calls a MVC controller method. The method succeeds in sending an email but goes into the error function and the error variable is null.
Why is it failing?
I tried getting more on the error using a different call but the alert does not appear when using it. I guess because the return is null and can't be resolved.
Here is the AngularJS controller method.
$scope.BookMySeat = function (UserName, SeatNo) {
if (UserName) {
// The UserName is not empty. Check to see of it exists.
dataService.ValidateUsername(UserName).success(function (output) {
if (output == -1)
{
// The user name does NOT exist. Do the insert to the table.
$scope.onclick = !$scope.onclick;
console.log(UserName + SeatNo);
dataService.InsertSeat(UserName, slotNum, SeatNo).success(function (output) {
$scope.bookedSeatList = output;
var imageCollection = new Array(totalseat);
$scope.images = imageCollection;
$scope.imageUrlNotBooked = "../Images/RED.jpg";
$scope.bookcollscope = $scope.bookedSeatList;
console.log($scope.bookcollscope);
var imageCollection1 = new Array($scope.bookedSeatList);
$scope.images1 = imageCollection1;
$scope.imageUrlBooked = "../Images/GREEN.jpg";
// Alert.
alert("Seat number " + SeatNo + " has been booked for : " + UserName);
//----------------------------------------------------------------------------------------------------------
// Send an email using a MVC controller method.
// - Using $http to call to a MVC controller method.
//----------------------------------------------------------------------------------------------------------
var encodedQueryString = encodeURIComponent('emailAddress') + '=' + encodeURIComponent('dc4444#hotmail.com') + '&' + encodeURIComponent('type') + '=' + encodeURIComponent('I') + '&' + encodeURIComponent('seatNbr') + '=' + encodeURIComponent(SeatNo) + '&' + encodeURIComponent('slotNbr') + '=' + encodeURIComponent(0);
$http.get("/Home/SendAlertEmail?" + encodedQueryString).success(function (data) {
// Alert.
alert("An insert email was sent.");
}).error(function (error) {
// Error alert.
alert("Something went wrong with the insert - SendEmail. " + error);
console.log(error);
});
//$http.get("/Home/SendAlertEmail?" + encodedQueryString).success(function (data) {
// // Alert.
// alert("An insert email was sent.");
//}).error(function (xhr) {
// // Error alert.
// alert("Something went wrong with the insert - SendEmail. Status: " + xhr.status + ". Response Text: " + xhr.responseText);
// console.log(error);
//});
}).error(function (output) {
$scope.error = true;
});
}
else
{
// The user name exists.
alert("That passenger name exists. Please enter a UNIQUE passenger name in order to book a seat.");
}
console.log(output);
}).error(function (output) {
$scope.error = true;
});
}
else
{
alert("The passenger name is empty. Please enter a passenger name in order to book a seat.");
}
}
Here is the MVC controller method.
public void SendAlertEmail([FromUri] string emailAddress, [FromUri]string type, [FromUri]int seatNbr, [FromUri]int slotNbr)
{
string strHtmlMessageBody = "";
NetworkCredential NetworkCred = new NetworkCredential();
System.Net.Mail.SmtpClient smtp = new SmtpClient();
try
{
MailMessage mm = new MailMessage();
mm.From = new MailAddress("xxxxx#hotmail.com");
mm.Subject = "From the BookSeat Portal. Passenger Seat Information.";
if (type == "I")
{
strHtmlMessageBody = "<p>Your passenger seat: " + seatNbr + " has been created by the system.</p>";
}
else
{
strHtmlMessageBody = "<p>Your passenger seat number: " + seatNbr + ", slot number: " + slotNbr + " has been deleted by the system.</p>";
}
mm.Body = strHtmlMessageBody;
mm.IsBodyHtml = true;
mm.To.Add(new MailAddress(emailAddress));
smtp.Host = "smtp.live.com";
smtp.EnableSsl = true;
smtp.UseDefaultCredentials = true;
smtp.Port = 587;
NetworkCred.UserName = "xxxxx#hotmail.com";
NetworkCred.Password = "yyyyyyy";
smtp.Credentials = NetworkCred;
smtp.Send(mm);
}
catch (SmtpException smtpEx)
{
throw new Exception("SMTP exception: " + smtpEx);
}
catch (Exception ex)
{
throw new Exception("Sending email exception: " + ex);
}
}
Here is the email sent.
This is my angular controller
//Save AddNewEmployee functionality
EDC.SaveNewEmployee = function () {
if (EDC.AddNewEmployeeFormValidator.validate()) {
var UserID = '0',
CandidateSubmit = '';
if (EDC.isEdit) {
UserID = EDC.rowIdToEdit;
}
EmployeeDetailService.SaveNewEmployee(EDC.NewEmpAdd, UserID, CandidateSubmit).then(function (response) {
//Close popup window
EDC.AddNewEmployeeWindow.data("kendoWindow").close();
//EDC.NewEmpSave = response;
EDC.EmployeeDetailsGrid.dataSource.read();
});
}
};
Andthis one is my MVC Controller.
public async Task<ActionResult> SavePermanentEmployee(Employee model)
{
//Sending mail to BU
string DisplayName = "New Employee";
//Sending mail to Employee
string EmpDisplayName = "Price credentials";
BAL_Employee objBalEmp = new BAL_Employee();
Price_PMS_DAL.Employee emp = new Price_PMS_DAL.Employee();
emp.ID = model.ID;
emp.EmpID = model.employeeID ?? Convert.ToString(model.employeeID).ToUpper();
emp.ReferredBy = model.referredby;
emp.DOJ = model.dateOfJoining;
emp.Status = 1;
emp.Email = model.email;
emp.BUID = model.businessUnitID;
emp.ShiftID = model.ShiftID;
emp.ModifiedBy = Session["EmpID"].ToString();
var lstNewEmployeeCreated = BAL_Employee.GetEmployees();
var result = lstNewEmployeeCreated.Where(s => s.employeeID == emp.EmpID).FirstOrDefault();
if (result != null)
{
return Json("Employee ID already exists.", JsonRequestBehavior.AllowGet);
}
else
{
int empSave = objBalEmp.UpdateEmployee(emp);
BAL_Login objBalLog = new BAL_Login();
if (empSave == 1)
{
TempData["Datarefresh"] = "refresh";
lstemp = null;
string[] datastr = emp.Email.Split(new string[] { "#" }, StringSplitOptions.None);
int empLoginSave = objBalLog.AddUser(new Price_PMS_DAL.Login { UserName = datastr[0].Trim(), EmpID = emp.EmpID, BUID = emp.BUID, ShiftID = emp.ShiftID });
if (empLoginSave == 1)
{
var data = BAL_Employee.FilterEmployeeByParam("Select TOP 1 * FROM Employee where Status=1 order by EmpID desc");
Price_PMS_DAL.Emp_Leave modelBal = new Price_PMS_DAL.Emp_Leave();
modelBal.EmpID = emp.EmpID;
int empLeavebalSave = objBalEmp.CreateEmployeeLLeaveBalRec(modelBal);
if (empLeavebalSave == 1)
{
Price_PMS_BAL.Models.BusinessUnit.BU Bus = BAL_BU.GetSPBUs().Where(b => b.ID == model.businessUnitID).First();
if (Bus != null)
{
//Sending Mail to BU when new Permanent employee added into the system
StringBuilder str = new StringBuilder();
StringBuilder cc = new StringBuilder();
StringBuilder to = new StringBuilder();
to.Append(#" " + Bus.BUHeadEmailId);
str.Append(#"Hello,<br><br> New Employee named <b>" + model.name + "</b> has been added to " + Bus.BUName + " BU " + " on " + DateTime.Now.ToShortDateString() + ".<br><br> Regards,<br> PRICE");
bool x = await Price_PMS_BAL.Models.Email.Email.SendEmail(cc, to, "New Employee Added", str.ToString(), DisplayName);
//End
}
//Sending Mail to Employee when new Permanent employee added into the system
if (emp != null)
{
StringBuilder str = new StringBuilder();
StringBuilder cc = new StringBuilder();
StringBuilder to = new StringBuilder();
to.Append(#" " + emp.Email);
//Username with last name Split
String[] Emailstring = emp.Email.Split(new[] { '#' });
String username = Emailstring[0];
//Username split with out last name
String[] Uname = username.Split(new[] { '.' });
String Unamestr = Uname[0];
Unamestr = Unamestr.Substring(0, 1).ToUpper() + Unamestr.Substring(1);
var PriceURL = "https://price.dreamorbit.com/";
str.Append(#"Hi " + Unamestr + ",<br><br> Welcome to DreamOrbit. Please login to PRICE (Projects, Resource Information & Cost Estimation) to apply for your leaves and to see your ratings etc. on a regular basis with following credentials:<br><br><br> <b><u>URL</u></b> : <a href=" + PriceURL + " target=_blank>" + PriceURL + "</a> <br> <b><u>Username</u></b> : " + username + "<br> <b><u>Password</u></b> : [Your System Password]<br><br><br> We wish you a long and mutually beneficial association with DreamOrbit. For any queries please reach out to Panchali (panchali.bharali#dreamorbit.com).<br><br> Regards,<br> PRICE");
bool x = await Price_PMS_BAL.Models.Email.Email.SendEmail(cc, to, "PRICE Credentials", str.ToString(), EmpDisplayName);
}
//End
return Json("Saved Successfully", JsonRequestBehavior.AllowGet);
}
else { return Json("Error occurred while saving data ", JsonRequestBehavior.AllowGet); }
}
else
return Json("Error occurred while saving data ", JsonRequestBehavior.AllowGet);
}
else
{
return Json("Error occurred while saving data ", JsonRequestBehavior.AllowGet);
}
}
}
Usually javascript code execute synchronously(default) and javascript has core promise object which is use to make function asynchronous.
Angularjs has core service $q which is use to make function asynchronous.
Angularjs simple example :
angular.module("starter", [])
.controller("myCtrl", function($scope, $q, $http){
var GetData = function(){
var root = 'https://jsonplaceholder.typicode.com';
var defer = $q.defer();
$http({
method: "GET",
url: root + '/posts/1'
}).then(function(response){
//success call back
defer.resolve(response);
}, function(error){
//error callbcall
defer.reject();
});
return defer.promise;
};
$scope.AsynchCall = function(){
GetData().then(function(response){
//success call back
console.log(response);
alert(JSON.stringify(response));
}, function(error){
//error callbcall
console.log(JSON.stringfy(error));
alert(error);
});
};
});
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
</head>
<body ng-app="starter" ng-controller="myCtrl">
<button ng-click="AsynchCall()"> Asynch call </button>
</body>
</html>
This is because JSON.stringify will return the return value of the toJSON function if it exists.
I'm using https://github.com/randdusing/cordova-plugin-bluetoothle/ firstly to scan devices and later to connect/read/write data in them.
The devices that i have to connect with are password protected but there is no input or parameter to include it.
I made the connection with the devices (without password) and everything seems to be OK but attempt to read data from the different devices is imposible.
The read data is encoded (base64) and after converting it to a String the result is " "
Any hint about this?
Connection:
$rootScope.connect = function(addressParam) {
var params = {address: addressParam};
$cordovaBluetoothLE.connect(params).then(null, function (obj) {
console.log("Conexión error " + obj.status + " con dirección: " + obj.address);
$rootScope.close(addressParam);
}, function (obj) {
console.log("Conexión success " + obj.status + " con dirección: " + obj.address);
$rootScope.isCon(addressParam);
if(obj.status==="disconnected" || obj.status==="undefined" ){
$rootScope.connect(addressParam);
}
});
}
Read:
$scope.readChar = function(){
var params = {address: $scope.device, service: $scope.service.uuid, characteristic: $scope.characteristic, timeout: 5000};
$cordovaBluetoothLE.read(params).then(function(obj) {
$scope.leer = true;
console.log("COMENZANDO LECTURA ");
$scope.valueobj = obj.value;
$scope.convertValue();
}, function(obj) {
console.log("Error al leer" + obj);
});
}
Conversion after reading
$scope.convertValue = function(){
$scope.bytesobj = $cordovaBluetoothLE.encodedStringToBytes($scope.valueobj);
$scope.strobj = $cordovaBluetoothLE.bytesToString($scope.bytesobj);
}
});
Results: No error:
$scope.bytesobj
--> [0, 0]
$scope.strobj
--> "
$scope.valueobj
--> "AAA="
I am using Parse for my app. I have two tables StudentDetail and Subject,as user enters his name, the id is queried from studentDetail table. and using that id i want to fetch rest of the details of Subject table.Data fetched through this code is correct but in $scope.subs i.e 19th line it overrides the data and returns only the last record,i want to store all the records in $scope.subs object iteratively.
$scope.subjectFetch= function(form,form1) {
var query = new Parse.Query(StudentDetail);
var querySub = new Parse.Query(Subject);
query.equalTo("Firstname",form1.Firstname);
query.find({
success: function(results) {
stdId = results[0].id;
querySub.equalTo("StudentId",stdId);
querySub.find({
success: function(subjects) {
alert("Success");
for (var i = 0; i < subjects.length; i++) {
var object = subjects[i];
subname = object.get('Name');
credits = object.get('credits');
code =object.get('code');
duration = object.get('duration');
alert("Subject name: "+subname+"\n Credits :"+credits+"\n Code :"+code+"\n Duration:"+duration);
$scope.subs=[{Name:subname,credits:credits,code:code,duration:duration},{Name:"xyz",credits:5}];
//console.log($scope.subs);
}
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
}
});
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
}
});
}
You are setting $scope.subs to be a new array with a single object in it inside your loop, which is why only the last one is there when it is done.
Try the following success handler instead:
success: function(subjects) {
// reset subs array
$scope.subs = [];
for (var i in subjects) {
var subject = subjects[i];
// push new object into the array
$scope.subs.push({
Name: subject.get('Name'),
credits: subject.get('credits'),
code: subject.get('code'),
duration: subject.get('duration')
});
}
// log the populated array
console.log($scope.subs);
Alternatively if you use something like the Underscore library, you can just map the items:
// replace success function body with this:
$scope.subs = _.map(subjects, function(subject) {
return {
Name: subject.get('Name'),
credits: subject.get('credits'),
code: subject.get('code'),
duration: subject.get('duration')
};
});
console.log($scope.subs);