express.JS .push cousing array to be undefined - javascript

Hi for some reason everytime i try to push data into my array i get a error returned saying the array is undefined
function getPosts(initial){
var data = {};
if ($scope.user){
data.ids = angular.copy($scope.user.friends);
data.ids.push($scope.user._id)
}
$http.post('api/social/getPost', data).success(function(response) {
if (initial) {
$scope.wallposts = response;
if (response.length == 0) {
getPosts(true);
} else {
$scope.wallposts = response;
}
} else {
if (response.length > $scope.wallposts.length) {
$scope.IncomingPosts = response;
}
}
});
};
this is the error
Error: data.ids is undefined
getPosts#http://localhost:3000/client/controllers/PostController.js:48:16
#http://localhost:3000/client/controllers/PostController.js:105:9
invoke#http://localhost:3000/node_modules/angular/angular.js:4604:16
$ControllerProvider/this.$get</</instantiate<#http://localhost:3000/node_modules/angular/angular.js:9855:24
nodeLinkFn#http://localhost:3000/node_modules/angular/angular.js:8927:34
compositeLinkFn#http://localhost:3000/node_modules/angular/angular.js:8226:13
compositeLinkFn#http://localhost:3000/node_modules/angular/angular.js:8229:13
compositeLinkFn#http://localhost:3000/node_modules/angular/angular.js:8229:13
compositeLinkFn#http://localhost:3000/node_modules/angular/angular.js:8229:13
nodeLinkFn#http://localhost:3000/node_modules/angular/angular.js:8973:1
compositeLinkFn#http://localhost:3000/node_modules/angular/angular.js:8226:13
publicLinkFn#http://localhost:3000/node_modules/angular/angular.js:8106:30
compilationGenerator/<#http://localhost:3000/node_modules/angular/angular.js:8447:20
createBoundTranscludeFn/boundTranscludeFn#http://localhost:3000/node_modules/angular/angular.js:8244:1
controllersBoundTransclude#http://localhost:3000/node_modules/angular/angular.js:9020:20
ngIfWatchAction#http://localhost:3000/node_modules/angular/angular.js:25059:15
$RootScopeProvider/this.$get</Scope.prototype.$digest#http://localhost:3000/node_modules/angular/angular.js:16664:23
$RootScopeProvider/this.$get</Scope.prototype.$apply#http://localhost:3000/node_modules/angular/angular.js:16928:13
done#http://localhost:3000/node_modules/angular/angular.js:11266:36
completeRequest#http://localhost:3000/node_modules/angular/angular.js:11464:7
requestLoaded#http://localhost:3000/node_modules/angular/angular.js:11405:1
however if i remove the line that pushed the id into the array everything works fine?
the code on the server side is
module.exports.getPosts = function(req, res){
//get all friends and users posts
Posts.find( {postedBy: {$in: req.body.ids}} )
.sort({postedOn: -1})
.exec(function(err, allPosts){
if (err) {
console.log(err)
} else {
res.json(allPosts)
}
});
};
all i am trying to do is gather all ids from the users friend then add the users id to the array so i can use a $in query to search mongo for all posts that have been created by them ids.
i have spent 5 days on this bug and to be honest i have no idea what is going on
here is the full code for the client side in case it helps
(function(){
angular.module('Scrimbox')
.controller('postsController', ['$scope', '$http', '$interval', '$routeParams', function( $scope, $http, $interval, $routeParams){
$scope.newPost = function(){
var request = {};
var user = JSON.parse(localStorage.getItem("User-Data"));
var userId = user["_id"];
var useravatar = user["avatar"];
var username = user["username"];
var request = {
postedBy: userId,
posts_avatar: useravatar,
username: username,
content: $scope.postContent
};
//send to server
$http.post('api/social/newPost', request).success(function(response){
getPosts(true);
}).error(function(error){
console.log(error);
});
};
function getPosts(initial){
var data = {};
if ($scope.user){
data.ids = angular.copy($scope.user.friends);
data.ids.push($scope.user._id)
}
$http.post('api/social/getPost', data).success(function(response) {
if (initial) {
$scope.wallposts = response;
if (response.length == 0) {
getPosts(true);
} else {
$scope.wallposts = response;
}
} else {
if (response.length > $scope.wallposts.length) {
$scope.IncomingPosts = response;
}
}
});
};
$interval(function(){
getPosts(false);
if ($scope.IncomingPosts) {
$scope.difference = $scope.IncomingPosts.length - $scope.wallposts.length;
}
console.log("this is working");
}, 5000);
$scope.newP = function(){
console.log('getting new posts');
$scope.wallposts = angular.copy($scope.IncomingPosts);
$scope.IncomingPosts = undefined;
}
//Init
getPosts(true);
}]);
}());

Answers by Molda.
So maybe $scope.user.friends is undefined the first time so
angular.copy assigns undefined to data.ids, quick fix could be after
data.ids = angular.copy($scope.user.friends); do this if(!data.ids ||
!data.ids.length) data.ids = []

Related

restore filtered state in angular controller when using back button?

I have order list page with a list of items and a set of filter options ( order state, order number, and date ) at the top of the page to filter the items. The user can click an item to view a detail page for the item.
When the user is on a detail and clicks their back button, it returns to the list, but with the filter options reset to default.
after doing some research o know that I can do it with with the Url the problem is I don't know how . please help me with that.
my controller
function searchOrders() {
$scope.isLoading = true;
model.noData = false;
model.isSearch = true;
model.orders = {};
QaDashboardService.searchOrders(model.filterByNumber, model.status, model.startFrom, model.startTo)
.then(function (orders) {
if(orders) {
$scope.isLoading = false;
model.orders = orders;
}
}).catch(function (error) {
$scope.isLoading = false;
model.noData = true;
});
}
QaDashboardService.js
function searchOrders(orderNumber, status, startFrom, startTo) {
service.data = [];
var deferred = $q.defer();
var orderCollection = service.db.collection("orders");
if (orderNumber) {
orderCollection = orderCollection.where("number", "==", orderNumber);
}
if (status && status != "*") {
orderCollection = orderCollection.where("status", "==", status);
}
if (startFrom && startTo) {
startFrom = new Date(startFrom).getTime();
startTo = new Date(startTo).getTime();
orderCollection = orderCollection.where("created", ">=", startFrom).where("created", "<=", startTo);
}
orderCollection.get().then(function (querySnapshot) {
if (!querySnapshot.empty) {
querySnapshot.forEach(function (doc) {
service.data.push(doc.data());
deferred.resolve(service.data);
});
} else {
deferred.reject("no data");
}
}).catch(function (error) {
deferred.reject(error);
});
return deferred.promise;
}
my app.js
.state('qa-dashboard.orders-list', {
url: "/orders-list",
module: "private",
templateUrl: "app/qa-dashboard/orders/orders-list/orders-list.html",
controller: 'OrdersListCtrl',
role: ['admin', 'QA'],
resolve: {
"allOrders": ["QaDashboardService", '$rootScope', function (QaDashboardService) {
return QaDashboardService.allOrders(40).then(
function (data) {
return data;
},
function (error) {
console.error("Error:", error);
}
);
}]
i tried this way and the url change but the filterd list is gone , it's like someone refresh the page
i change the url in app.js to be like this
url: "/orders-list/:pageName"
I applied this function in QaDashboardService.js
function openPage (pageName) {
$state.go('qa-dashboard.orders-list',{'pageName':pageName});
};
i called it in search function
function searchOrders(orderNumber, status, startFrom, startTo) {
service.data = [];
var deferred = $q.defer();
var orderCollection = service.db.collection("orders");
if (orderNumber) {
orderCollection = orderCollection.where("number", "==", orderNumber);
service.openPage(orderNumber);
}
if (status && status != "*") {
orderCollection = orderCollection.where("status", "==", status);
service.openPage(status);
}
if (startFrom && startTo) {
startFrom = new Date(startFrom).getTime();
startTo = new Date(startTo).getTime();
orderCollection = orderCollection.where("created", ">=", startFrom).where("created", "<=", startTo);
}
orderCollection.get().then(function (querySnapshot) {
if (!querySnapshot.empty) {
querySnapshot.forEach(function (doc) {
service.data.push(doc.data());
deferred.resolve(service.data);
});
} else {
deferred.reject("no data");
}
}).catch(function (error) {
deferred.reject(error);
});
return deferred.promise;
}
but it didn't work it
i also tried $location and didn't work either

Client-side authentication using AngularJS

I have created login page and trying to do client-side authentication. I know it's a bad practice, but I want to learn it. I am accessing the data using JSON server. When I submit the button , my data is getting posted in the server, but I am failing when I am trying to match the content on success call. Please let me know what I am doing wrong.
Any help / advice would be greatly appreciated.
AngularJS :
app.factory('Authentication', function($http, $q, session) {
var service = {};
service.isAuthenticated = function() {
return isAuthenticated = false,
username = ""
};
service.login = function(username, password) {
return $q(function(resolve, reject) {
$http.post('http://localhost:3000/loginfo', {
username,
password
})
.then(
function successCallback(response) {
var data = response.data;
var user = {};
for (var i = 0; i < data; i++) {
alert('go');
if (data[i].username === username && data[i].password === password) {
user = data[i];
break;
}
}
session.create(response.data.id, response.data.username);
resolve(response.data);
console.log(response.data)
},
function(err) {
reject(err);
});
});
};
return service;
});
/* client-side */
app.controller('credientials', function($scope, $http, auth) {
$scope.userCred = {
username: '',
password: ''
};
/*-----Form Submition-----*/
$scope.log = function(userCred) {
$scope.isAuthenticated = true;
Authentication.login(userCred.username, userCred.password)
.then(function(result) {
console.log(result);
}, function(err) {
console.error(err);
});
};
}]);

cannot access the .id value of a resource

Trying to access $scope.mySlot.id but it is undefined.
$scope.removeMe = function() {
var shouldRemove = confirm('Remove you from this field trip?');
if (shouldRemove) {
var data = null;
UserService.me().then(function(me){
var data = {userID: me.id, eventID: tripID}
console.log(data);
return data;
}).then (function(data){
var mySlot = GreenTripFilledSlotsFactory.get(data);
return mySlot;
}).then (function(mySlot) {
$scope.mySlot = mySlot;
console.log("this is $scope.mySlot: ");
console.log($scope.mySlot); //this shows up as a resource with proper values
console.log("this is $scope.mySlot.id: ")
console.log($scope.mySlot.id); //this is undefined
}).then (function(success){
return $scope.mySlot.$delete(); // this isn't working'
}).then(function(success){
console.log('mySlot deleted');
route.reload();
}).catch(function(error){
console.log(error);
})
}
};
In the console.logs $scope.mySlot is shown as a resource and it does list the values of it. But I'm confused why $scope.mySlot.id is undefined.
FACTORIES:
.factory('GreenTripSlotsFactory', ['$resource', function($resource) {
return $resource('/api/GreenTripSlots/:id/', {id: '#id' }, {
update: {method: 'PUT' }
});
}])
.factory('GreenTripFilledSlotsFactory', ['$resource',
function($resource) {
return $resource('/api/GreenTripSlots/:userID/:eventID/:slotID',
{id: '#id' }, {
update: {method: 'PUT' }
});
}])
BACKEND contollers:
// = /api/GreenTripSlots/:userID/:eventID
router.route('/:userID/:eventID')
.get(function(req,res) {
procedures.procGetSlotByUserAndTrip(req.params.userID,
req.params.eventID).then(function(greenTripUserSlot){
res.send(greenTripUserSlot);
}, function(err) {
console.log(err);
res.sendStatus(500);
})
})
// = /api/GreenTripSlots:/userID/:eventID/:slotID
router.route('/:userID/:eventID/:slotID')
.get(function(req,res) {
procedures.procGetSlotByUserAndTrip(req.params.userID,
req.params.eventID).then(function(greenTripUserSlot){
res.send(greenTripUserSlot);
}, function(err) {
console.log(err);
res.sendStatus(500);
})
})
.delete(function(req, res){
procedures.procRemoveMe(req.params.slotID).then(function(){
res.sendStatus(204);
}, function(err) {
console.log(err);
res.sendStatus(500);
});
})
Backend Procedures:
exports.procGetSlotByUserAndTrip = function(userID, eventID) {
return db.fnRow('procGetSlotByUserAndTrip', [userID, eventID])
}
exports.procRemoveMe = function(slotID) {
return db.fnEmpty('procRemoveMe', [slotID])
SQL Stored Procedure for Get:
CREATE DEFINER=`CharleyHannah`#`localhost` PROCEDURE
`procGetSlotByUserAndTrip`(pUserId INT, pEventId INT)
BEGIN
SELECT *
FROM userEvents u
WHERE u.userID = pUserId & u.eventID = pEventId;
END
SQL Stored Procedure for delete:
CREATE DEFINER=`CharleyHannah`#`localhost` PROCEDURE
`procRemoveMe`(pSlotId int)
BEGIN
DELETE
FROM userEvents
WHERE id = pSlotId;
END
Your function GreenTripFilledSlotsFactory.get(data); returns a promise. You can write something like that:
var _promise = GreenTripFilledSlotsFactory.get(data);
_promise.then(function(res) {
$scope.mySlot = res;
console.log($scope.mySlot.id); //should display your value now
});
In the res Variable your object is stored.
You assign userToRemove outside the promise then and it's executed before $scope.ME assingning.
Instead of using the factories, I had success in just using $http.get and $http.delete requests:
$scope.removeMe = function() {
var shouldRemove = confirm('Remove you from this field trip?');
if (shouldRemove) {
var data = null;
UserService.me().then(function(me){
var data = {eventID: tripID, userID: me.id}
console.log(data);
return data;
}).then (function(data){
var mySlot = $http.get('/api/GreenTripSlots/' + data.eventID + '/' + data.userID);
console.log(mySlot);
return mySlot;
}).then (function(mySlot) {
var slotToDelete = mySlot.data;
console.log(slotToDelete);
console.log(slotToDelete.id)
return slotToDelete;
}).then (function(slotToDelete){
var slotID = slotToDelete.id;
$http.delete('/api/GreenTripSlots/delete/' + slotID);
console.log('deleted successfully')
$route.reload();
}).catch(function(error){
console.log(error);
})
}
};
}])

angularjs rewrite controller without factory

i'm developing an app that received from a server a JSON array and divided data in a specific way, i've a portion of code that works if i use it alone but if i tried to insert it in an application it doesn't work.
This is my code:
ionicApp.controller('DefaultController', DefaultController)
.factory('dataService', dataService);
DefaultController.$inject = ['dataService', '$http'];
function DefaultController(dataService, $http) {
var vm = this;
console.log("Dentro ctrl");
getEvents();
function getEvents() {
console.log("Dentro getEvents");
return dataService.getEvents()
.then(function (data) {
console.log("data: " + data);
vm.data = data;
console.log("vm.data: " + vm.data);
return vm.data;
});
}
vm.submit = function (){
console.log("funzione");
console.log(vm.form);
var data = vm.form; // IMPORTANT
//console.clear();
var link = 'http://localhost/<path>/api/apiDoFix.php';
var mail = window.localStorage.getItem("mail");
var scelta = window.localStorage.getItem("scelta");
console.log(data);
console.log ("EMAIL" + mail);
console.log ("SCELTA" + scelta);
$http.post(link, {giorno: data.giorno, ora: data.ora, mail: mail, scelta: scelta})
.then(function (res){
console.log("Dentro http.post");
var response = res.data;
if (response != 'F'){
console.log("Dentro if");
console.log(response);
//window.location.href ="/#/main";
} else {
console.log("Dentro else");
}
});
};
}
dataService.$inject = ['$http'];
function dataService($http) {
console.log("qua");
var service = {
getEvents: getEvents
};
return service;
function getEvents() {
console.log("qua2");
var config = {
transformResponse: function (data, headers) {
var result = {
events: [],
schedules: []
};
var events = JSON.parse(data);
var dates = [];
console.log("qua3");
for (var i = 0; i < events.length; i++) {
if (dates.indexOf(events[i].day) === -1) {
var date = events[i].day;
dates.push(date);
result.events.push({
date: date
});
}
result.schedules.push({
date: events[i].day,
time: events[i].time
});
}
console.log("result: " + result);
return result;
}
};
return $http.get('http://localhost/ShuttleFIX/api/apiTimes.php', config)
.then(getEventsCompleted)
.catch(getEventsFailed);
function getEventsCompleted(response) {
console.log("response " + response.data);
return response.data;
}
function getEventsFailed(error) {
console.error(error);
}
}
}
is it possible to rewrite this code in a controller function without using factory?
Thank's

how can I put an item with checked = true depending on the info in the DB?

I have a list of items with the option to checked or unchecked them. I am doing a post request in order to save the unchecked items, and that post request works great, but I am having an issue with the get request, the front-end retrieves fine the info from the back-end, but I have this function which is putting on checked = true the items without taking care of the unchecked items saved already
if (sports.length) {
$scope.sports = _.map(sports, function(sport) {
sport.checked = true;
return sport;
});
};
so, if the user refreshes the page, all items get back to checked = true due to the function above. So how can I do to persist the items with checked or unchecked ? what do I have to change in that function in order to persist that data ?
this is my code regarding the get request of that data
I am using lodash, just in case...
front-end
controller.js
please read the note in this code
.controller('SportsController', function($scope, SportsFactory, AuthFactory) {
$scope.sports = [];
SportsFactory.getSportChecked(customer).then(function(sportChecked) {
_.each(sports, function(sport) {
var sportIds = _.pluck(sports, 'id'),
intersectedSports = _.intersection(sportIds, sportChecked),
checkedSportObjects = _.filter(sport, function(sportObj) {
return _.includes(intersectedSports, sportObj);
});
_.each(checkedSportObjects, function(sport) {
$scope.sports.push(sport);
});
});
}
//this is the function putting checked = true with out taking care
//of what the back-end returns
if (sports.length) {
$scope.sports = _.map(sports, function(sport) {
sport.checked = true;
return sport;
});
}
$scope.toggleSportSelection = function(sport) {
var params = {};
params.user = $scope.customer.customer;
params.sport = sport.id;
sport.checked = !sport.checked;
SportsFactory.setSportChecked(params);
};
});
service.js
.factory('SportsFactory', function($http, $q, AuthFactory,
LocalForageFactory, CONSTANT_VARS) {
return {
getSportChecked: function(customer) {
var defer = $q.defer(),
user,
rejection = function(err) {
console.log(err);
defer.reject(err);
};
LocalForageFactory.retrieve(CONSTANT_VARS.LOCALFORAGE_SPORTS_CHECKED)
.then(function(sportChecked) {
user = customer.customer;
if (!_.isNull(sportChecked)) {
defer.resolve(sportChecked);
}else {
$http.get(CONSTANT_VARS.BACKEND_URL + '/sports/getChecked/' + user)
.success(function(sportChecked) {
LocalForageFactory.set(CONSTANT_VARS.LOCALFORAGE_SPORTS_CHECKED, sportChecked);
defer.resolve(sportChecked);
})
.error(rejection);
}
}, rejection);
return defer.promise;
}
}
});
BACK-END - node.js/sails.js
SetSportsController
module.exports = {
retrieveSetCheck: function(req, res) {
if (req.params) {
SportSelectionService.getSportChecked(req.params).then(function(sportChecked) {
res.json(200, sportChecked);
}, function(err) {
res.json(400, err);
});
}else {
res.json(400, {error: 'Error retrieving Sports'});
}
}
}
SportSelectionService
module.exports = {
getSportChecked: function(params) {
var Promise = require('bluebird');
return new Promise(function(fullfill, reject) {
console.time('sportChecked_findOne');
SportSelection.find({
user: params.user
}).exec(function(err, sportChecked) {
console.timeEnd('sportChecked_findOne');
if (err) {
reject(new Error('Error finding sportChecked'));
console.error(err);
}else {
if (sportChecked) {
fullfill(sportChecked);
}else {
console.time('sportChecked_create');
SportSelection.create({
sport: [],
user: params.user
}).exec(function(err, created) {
console.timeEnd('sportChecked_create');
console.log(err);
console.log(created);
if (err) {
reject(new Error('Error on sportChecked'));
}else {
fullfill(created);
}
});
}
}
});
});
}
}

Categories