Client-side authentication using AngularJS - javascript

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);
});
};
}]);

Related

Unable to store cookies and allow session

I'm trying to create a simple ticketing app.
Once the user logins it should show a dashboard with project name and 3 categories of tickets count and a add ticket button to add a new ticket
Problem I'm able to authenticate the user on login screen but when it navigates to the next screen that is dashboard the user get unauthenticated hence not able to fetch api and display the data being sent
index.js
var app = angular.module("loginTest", ["ngRoute"]);
app.config(function ($routeProvider) {
$routeProvider
// login view definition
.when("/login", {
controller: "loginController",
controllerAs: "vm",
templateUrl: "login.html"
})
.when("/main", {
controller: "mainController",
controllerAs: "vm",
templateUrl: "main.html",
authenticated:true
})
.when("/setting", {
controller: "settingController",
controllerAs: "vm",
templateUrl: "project.html",
authenticated:true
})
.when("/about", {
controller: "aboutController",
controllerAs: "vm",
templateUrl: "about.html",
authenticated:true
})
.when("/addTicket",{
controller:"addTicketCtrl",
controllerAs:"vm",
templateUrl:"addTicket.hmtl",
authenticated:true
})
.otherwise({
redirectTo: "/main",
authenticated:true
});
});
app.run(function ($rootScope, $location) {
$rootScope.$on("$routeChangeStart", function (event, next) {
// check current login status and filter out if navigating to login
if (!$rootScope.loggedIn && next.originalPath !== "/login") {
// remember the original url
$location.url("/login?back=" + $location.url());
}
});
});
app.config(['$qProvider', function ($qProvider) {
$qProvider.errorOnUnhandledRejections(false);
}]);
app.service("loginService",$cookies, function ($http, $cookies) {
console.log("service");
$cookies.get(email),
$cookies.get(password)
return {
checkLogin: function () {
return $http.post("/login").then(function (response) {
console.log(response.data);
return response.data;
});
},
login: function (email, pass, $cookies) {
console.log("loginn fucntion");
return $http.post("https://qa.workdaysync.io/getcadentapi/auth/login", {
email: email,
password : pass,
}).then(function (response) {
//console.log("1st response"+response.status);
return response.data;
}, function (response) {
var err = new Error(response.statusText);
//console.log("2st response" +response.errorCode);
err.code = response.status;
if (response.status == 401) {
var error = "USERNAME OR PASSWORD IS INCORRECT"
var loginfailed = true;
//alert(error);
//console.log(loginfailed);
}
throw err;
});
}
};
})
/* app.service("addTicketService",function($rootScope,$http){
var vm=this;
addTicket: function (description){
return $http.post("https://qa.workdaysync.io/getcadentapi/tickets", {
description: description,
id: name
}).then(function (response) {
//console.log("1st response"+response.status);
return response.data;
console.log(response.data);
}
})
}); */
app.controller("loginController",$cookies, function ($rootScope, $location, loginService,$cookies) {
var vm = this;
function success() {
$rootScope.loggedIn = true;
$rootScope.loginError = false;
$cookies.put('username', email);
$cookies.put('password', password);
var back = $location.search().back || "";
$location.url(back !== "/login" ? back : "");/*
$cookies.put('username', email);
$cookies.put('password', password); */
}
function failure() {
$rootScope.loggedIn = false;
$rootScope.loginError = true;
}
loginService.checkLogin().then(success);
vm.login = function () {
loginService.login(vm.user, vm.pass).then(success, failure);
};
vm.logout = function () {
loginService.logut(
localStorage.clear(),
sessionStorage.clear()
);
}
})
app.service('HttpService', function ($http) {
return {
getPost: function () {
// $http returns a promise, which has a then function, which also returns a promise.
return $http.get('https://qa.workdaysync.io/getcadentapi/sync')
.then(function (response) {
// In the response, resp.data contains the result. Check the console to see all of the data returned.
console.log('Get Post', response);
return response.data;
});
},
getUsers: function () {
// $http returns a promise, which has a then function, which also returns a promise.
return $http.get('https://qa.workdaysync.io/getcadentapi/sync')
.then(function (response) {
// In the response, resp.data contains the result. Check the console to see all of the data returned.
console.log('Get Users', response);
return response.data;
});
}
}
});
app.controller('mainController', function ($scope, HttpService) {
HttpService.getPost()
.then(function (response) {
$scope.post = response;
});
HttpService.getUsers()
.then(function (response) {
$scope.users = response;
console.log("asdfdsfsdf");
console.log("umm"+ $scope.users.inProgressCount);
console.log("asdfdsfsdf++++sdsad");
var myNumber = $scope.users.inProgressCount;
var formattedNumber = ("0" + myNumber).slice(-2);
console.log(formattedNumber);
});
});
app.filter('counterValue', function(){
return function(value){
value = parseInt(value);
if(!isNaN(value) && value >= 0 && value < 10)
{return "0"+ value;
return "";
}else{
return value;
return "";
}
}
})
server.js
var express = require("express");
var cookieSession = require('cookie-session');
var bodyParser = require("body-parser");
var session = require("express-session");
var app = express();
app.use(express.static("app"));
app.use(cookieSession({
secret: '1234567qwerty',
signed: true,
}));
app.use(session({
cookie: {
maxAge: 60 * 10
},
resave: false,
rolling: true,
saveUninitialized: true,
secret: "COOKIE_SECRET"
}));
app.use(bodyParser.json());
app.get("/login", function (req, res, _next) {
console.log(req.session.id);
var email = req.body.email;
var pass = req.body.pass;
if (email == req.session.user && pass == req.session.pass) {
res.status(401).end();
console.log("Inside login else logic" + req.body.email);
} else {
req.session.user = req.body.email;
req.session.password = req.body.password;
console.log("Inside login if logic" + req.body.email);
res.end();
}
});
app.get("/me", function (req, res, next) {
console.log(req.session.id);
if (req.session.user) {
res.send(req.session.user);
} else {
res.status(405).end();
console.log("status");
}
});
var server = app.listen(4000, function () {
console.log("Sample login server running");
});
It should login and then display the ticket raised count and when clicked on add ticket button the cookie should be valid

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);
})
}
};
}])

How to get username of currenlty logged on user authservice

I would like to get the currently loged in username so i can display it. But i dont know how to do it ? Any ideas ? I am using authservice Here is my angular controller in which i would like to get the username.
myApp.controller('meetupsController', ['$scope', '$resource', function ($scope, $resource) {
var Meetup = $resource('/api/meetups');
$scope.meetups = []
Meetup.query(function (results) {
$scope.meetups = results;
});
$scope.createMeetup = function () {
var meetup = new Meetup();
meetup.name = $scope.meetupName;
meetup.$save(function (result) {
$scope.meetups.push(result);
$scope.meetupName = '';
});
}
}]);
my main angular controller code
var myApp = angular.module('myApp', ['ngResource', 'ngRoute']);
myApp.config(function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'partials/main.html',
access: {restricted: true}
})
.when('/api/meetups', {
templateUrl: 'partials/main.html',
access: {restricted: true}
})
.when('/login', {
templateUrl: 'partials/login.html',
controller: 'loginController',
access: {restricted: false}
})
.when('/prive', {
templateUrl: 'partials/prive.html',
controller: 'userController',
access: {restricted: true}
})
.when('/logout', {
controller: 'logoutController',
access: {restricted: true}
})
.when('/register', {
templateUrl: 'partials/register.html',
controller: 'registerController',
access: {restricted: false}
})
.when('/one', {
template: '<h1>This is page one!</h1>',
access: {restricted: true}
})
.when('/two', {
template: '<h1>This is page two!</h1>',
access: {restricted: false}
})
.otherwise({
redirectTo: '/'
});
});
myApp.run(function ($rootScope, $location, $route, AuthService) {
$rootScope.$on('$routeChangeStart',
function (event, next, current) {
AuthService.getUserStatus()
.then(function(){
if (next.access.restricted && !AuthService.isLoggedIn()){
$location.path('/login');
$route.reload();
}
});
});
});
myApp.controller('meetupsController', ['$scope', '$resource', function ($scope, $resource) {
var Meetup = $resource('/api/meetups');
$scope.meetups = []
Meetup.query(function (results) {
$scope.meetups = results;
});
$scope.createMeetup = function () {
var meetup = new Meetup();
meetup.name = $scope.meetupName;
meetup.$save(function (result) {
$scope.meetups.push(result);
$scope.meetupName = '';
});
}
}]);
my second angular code :
var app = angular.module('myApp');
app.controller('loginController',
['$scope', '$location', 'AuthService',
function ($scope, $location, AuthService) {
$scope.login = function () {
// initial values
$scope.error = false;
$scope.disabled = true;
// call login from service
AuthService.login($scope.loginForm.username, $scope.loginForm.password)
// handle success
.then(function () {
$location.path('/');
$scope.disabled = false;
$scope.loginForm = {};
})
// handle error
.catch(function () {
$scope.error = true;
$scope.errorMessage = "Invalid username and/or password";
$scope.disabled = false;
$scope.loginForm = {};
});
};
$scope.posts = [];
$scope.newPost = {created_by: '', text: '', created_at: ''};
$scope.post = function(){
$scope.newPost.created_at = Date.now();
$scope.posts.push($scope.newPost);
$scope.newPost = {created_by: '', text: '', created_at: ''};
};
}]);
app.controller('logoutController',
['$scope', '$location', 'AuthService',
function ($scope, $location, AuthService) {
$scope.logout = function () {
// call logout from service
AuthService.logout()
.then(function () {
$location.path('/login');
});
};
$scope.gotoregister = function () {
$location.path('/register');
};
$scope.gotoprive = function () {
$location.path('/prive');
};
}]);
app.controller('registerController',
['$scope', '$location', 'AuthService',
function ($scope, $location, AuthService) {
$scope.register = function () {
// initial values
$scope.error = false;
$scope.disabled = true;
// call register from service
AuthService.register($scope.registerForm.username, $scope.registerForm.password)
// handle success
.then(function () {
$location.path('/login');
$scope.disabled = false;
$scope.registerForm = {};
})
// handle error
.catch(function () {
$scope.error = true;
$scope.errorMessage = "Something went wrong!";
$scope.disabled = false;
$scope.registerForm = {};
});
};
}]);
and my services
angular.module('myApp').factory('AuthService',
['$q', '$timeout', '$http',
function ($q, $timeout, $http) {
// create user variable
var user = null;
// return available functions for use in the controllers
return ({
isLoggedIn: isLoggedIn,
getUserStatus: getUserStatus,
login: login,
logout: logout,
register: register
});
function isLoggedIn() {
if(user) {
return true;
} else {
return false;
}
}
function getUserStatus() {
return $http.get('/user/status')
// handle success
.success(function (data) {
if(data.status){
user = true;
} else {
user = false;
}
})
// handle error
.error(function (data) {
user = false;
});
}
function login(username, password) {
// create a new instance of deferred
var deferred = $q.defer();
// send a post request to the server
$http.post('/user/login',
{username: username, password: password})
// handle success
.success(function (data, status) {
if(status === 200 && data.status){
user = true;
deferred.resolve();
} else {
user = false;
deferred.reject();
}
})
// handle error
.error(function (data) {
user = false;
deferred.reject();
});
// return promise object
return deferred.promise;
}
function logout() {
// create a new instance of deferred
var deferred = $q.defer();
// send a get request to the server
$http.get('/user/logout')
// handle success
.success(function (data) {
user = false;
deferred.resolve();
})
// handle error
.error(function (data) {
user = false;
deferred.reject();
});
// return promise object
return deferred.promise;
}
function register(username, password) {
// create a new instance of deferred
var deferred = $q.defer();
// send a post request to the server
$http.post('/user/register',
{username: username, password: password})
// handle success
.success(function (data, status) {
if(status === 200 && data.status){
deferred.resolve();
} else {
deferred.reject();
}
})
// handle error
.error(function (data) {
deferred.reject();
});
// return promise object
return deferred.promise;
}
}]);
So this should probably work, maybe you will need to make some small adjustments because i don't know how exactly is your app structured, but this will work.
First you need to change your AuthService to look like this
angular.module('myApp').factory('AuthService',
['$q', '$timeout', '$http',
function ($q, $timeout, $http, $cookies) {
// create user variable
var user = null;
// we must create authMemberDefer var so we can get promise anywhere in app
var authenticatedMemberDefer = $q.defer();
// return available functions for use in the controllers
return ({
isLoggedIn: isLoggedIn,
getUserStatus: getUserStatus,
login: login,
logout: logout,
register: register,
getAuthMember: getAuthMember,
setAuthMember: setAuthMember
});
function isLoggedIn() {
if(user) {
return true;
} else {
return false;
}
}
//this is function that we will call each time when we need auth member data
function getAuthMember() {
return authenticatedMemberDefer.promise;
}
//this is setter function to set member from coockie that we create on login
function setAuthMember(member) {
authenticatedMemberDefer.resolve(member);
}
function getUserStatus() {
return $http.get('/user/status')
// handle success
.success(function (data) {
if(data.status){
user = true;
} else {
user = false;
}
})
// handle error
.error(function (data) {
user = false;
});
}
function login(username, password) {
// create a new instance of deferred
var deferred = $q.defer();
// send a post request to the server
$http.post('/user/login',
{username: username, password: password})
// handle success
.success(function (data, status) {
if(status === 200 && data.status){
user = true;
deferred.resolve();
//**
$cookies.putObject('loginSession', data);
// here create coockie for your logged user that you get from this response, im not sure if its just "data" or data.somethingElse, check you response you should have user object there
} else {
user = false;
deferred.reject();
}
})
// handle error
.error(function (data) {
user = false;
deferred.reject();
});
// return promise object
return deferred.promise;
}
function logout() {
// create a new instance of deferred
var deferred = $q.defer();
// send a get request to the server
$http.get('/user/logout')
// handle success
.success(function (data) {
user = false;
deferred.resolve();
//on log out remove coockie
$cookies.remove('loginSession');
})
// handle error
.error(function (data) {
user = false;
deferred.reject();
});
// return promise object
return deferred.promise;
}
function register(username, password) {
// create a new instance of deferred
var deferred = $q.defer();
// send a post request to the server
$http.post('/user/register',
{username: username, password: password})
// handle success
.success(function (data, status) {
if(status === 200 && data.status){
deferred.resolve();
} else {
deferred.reject();
}
})
// handle error
.error(function (data) {
deferred.reject();
});
// return promise object
return deferred.promise;
}
}]);
after that changes in authService, you must make this on your app run, so each time application run (refresh) it first check coockie to see if there is active session(member) and if there is it will set it inside our AuthService.
myApp.run(function($rootScope, $location, $route, AuthService, $cookies) {
$rootScope.$on('$routeChangeStart',
function(event, next, current) {
if ($cookies.get('loginSession')) {
var session = JSON.parse($cookies.get('loginSession'));
AuthService.setAuthMember(session);
} else {
$location.path('/login');
}
});
});
And simply anywhere where you want to get auth member you have to do this, first include in your controller/directive AuthService and do this
AuthService.getAuthMember().then(function(member){
console.log(member);
//here your member should be and you can apply any logic or use that data where u want
});
I hope this helps you, if you find any difficulties i'm happy to help
just a demo example
in login controller
var login = function(credentials) {
AuthService.login(credentials).then(function(result) {
var user = result.data;
AuthService.setCurrentUser(user);
$rootScope.$broadcast(AUTH_EVENTS.loginSuccess);
}).catch(function(err) {
if (err.status < 0) {
comsole.error('Please check your internet connection!');
} else {
$rootScope.$broadcast(AUTH_EVENTS.loginFailed);
}
});
};
in AuthService
.factory('AuthService', function($http, $cookies, BASE_URL) {
var service = {
login: function(formdata) {
return $http.post(BASE_URL + '/login', formdata);
},
setCurrentUser: function(user) {
$cookies.putObject('currentUser', user);
},
isAuthenticated: function() {
return angular.isDefined($cookies.getObject('currentUser'));
},
getFullName: function() {
return $cookies.getObject('currentUser').firstName + ' ' + $cookies.getObject('currentUser').lastName;
}
}
return service;
});
in the controller which attached with your dashboard view
$scope.$watch(AuthService.isAuthenticated, function(value) {
vm.isAuthenticated = value;
if (vm.isAuthenticated) {
vm.fullName = AuthService.getFullName();
vm.currentUser = AuthService.getCurrentUser();
}
});
There are few methods how you can get currently logged user, it mostly depends on you app structure and API, you probably should have API end point to get authenticated member and that call is made on each app refresh.
Also if you can show us your authservice.
Edit:
Also on successful login you can store information about logged user in coockie like this
function doLogin(admin) {
return authMemberResources.login(details).then(function(response) {
if (response) {
$cookies.putObject('loginSession', response);
} else {
console.log('wrong details');
}
});
So basically you can use angularjs coockies service and make loginSession coockie like that, and on app refresh or anywhere where you need logged user info, you can get that like this:
if ($cookies.get('loginSession')) {
var session = JSON.parse($cookies.get('loginSession'));
console.log(session);
}
.factory('AuthService', function($http, $cookies, BASE_URL) {
var service = {
login: function(formdata) {
return $http.post(BASE_URL + '/login', formdata);
},
setCurrentUser: function(user) {
$cookies.putObject('currentUser', user);
},
isAuthenticated: function() {
return angular.isDefined($cookies.getObject('currentUser'));
},
getFullName: function() {
return $cookies.getObject('currentUser').firstName + ' ' + $cookies.getObject('currentUser').lastName;
},
getAuthenticatedMember: function() {
if ($cookies.get('currentUser')) {
return JSON.parse($cookies.get('currentUser'));
}
}
}
return service;
});
That should work, i added new function getAuthenticatedMember and you can use it where you need it. And you can use it like this:
$scope.$watch(AuthService.isAuthenticated, function(value) {
vm.isAuthenticated = value;
if (vm.isAuthenticated) {
vm.currentUser = AuthService.getAuthenticatedMember();
}
});

Making Sync calls using promises Angular JS factories

I am trying to make sync calls using a factory pattern.
$scope.doLogin = function (username, password, rememberme) {
appKeyService.makeCall().then(function (data) {
// data = JSON.stringify(data);
debugAlert("login controller app key service"+data);
var appkeyvalue = data.d.appkey;
sessionConfigurationService.setBasicToken(appkeyvalue);
loginService.makeCall(username, password, rememberme).then(function (accessTokenData) {
if (accessTokenData.access_token !== "")
{
sessionConfigurationService.setAccessTokenData(accessTokenData.access_token);
userPreferencesService.makeCall().then(function (userPreferencesData) {
if (userPreferencesData.d.userId !== "")
{
sessionConfigurationService.setUserPreferences(userPreferencesData.d);
// $window.location.href = '/base.html';
}
});
}
});
});
};
My appKeyService factory is
app.factory('appKeyService', function ($q, authenticatedServiceFactory, configurationService) {
var deffered = $q.defer();
var service = {};
service.makeCall = function () {
debugAlert("appKeyService async method request start");
authenticatedServiceFactory.makeCall("GET", configurationService.getAppKeyURL(), "", "").then(function (data) {
debugAlert("appKeyService async method response")
deffered.resolve(data);
});
return deffered.promise;
};
return service;
});
My authenticated service factory is
app.factory('authenticatedServiceFactory', function ($http, $q, sessionConfigurationService) {
var deffered = $q.defer();
var service = {};
service.makeCall = function (methodType, URL, data, authType) {
var headerValue = "";
if (authType === "Basic") {
headerValue = sessionConfigurationService.getBasicToken();
} else if (authType === "Bearer") {
headerValue = sessionConfigurationService.getBearerToken();
}
var config = {headers: {
'Authorization': headerValue,
'Accept': 'application/json;odata=verbose',
},
withCredentials: true,
async: false
};
if (methodType === "GET") {
$http.get(URL, data, config)
.then(function (getData) {
debugAlert("GET method response" + JSON.stringify(getData));
deffered.resolve(getData.data);
}, function (error) {
debugAlert("GET method response error" + JSON.stringify(error));
deffered.reject(error);
});
}
else if (methodType === "POST") {
$http.post(URL, data, config)
.then(function (putData) {
debugAlert("POST method response" + JSON.stringify(putData));
deffered.resolve(putData.data);
}, function (error) {
debugAlert("POST method response error" + JSON.stringify(error));
deffered.reject(error);
});
}
else if (methodType === "DELETE") {
$http.delete(URL, data, config)
.then(function (deleteData) {
debugAlert("DELETE method response" + JSON.stringify(deleteData));
deffered.resolve(deleteData.data);
}, function (error) {
debugAlert("DELETE method response error" + JSON.stringify(error));
deffered.reject(error);
});
}
else if (methodType === "PUT") {
$http.put(URL, config)
.then(function (putData) {
debugAlert("PUT method response" + JSON.stringify(putData));
deffered.resolve(putData.data);
}, function (error) {
debugAlert("PUT method response error" + JSON.stringify(error));
deffered.reject(error);
});
}
return deffered.promise;
};
return service;
});
But I don't see the service calls are made in sync. So the "then" part in the controller is not executing after we receive the response. Its executing one after the other. How can I make that happen.
#Frane Poljak
Thank you for your comment. I just brought
var deffered = $q.defer();
inside the makeCall method and its working as I wanted now. Thank you!
app.factory('appKeyService', function ($q, authenticatedServiceFactory, configurationService) {
var service = {};
service.makeCall = function () {
var deffered = $q.defer();
debugAlert("appKeyService async method request start");
authenticatedServiceFactory.makeCall("GET", configurationService.getAppKeyURL(), "", "").then(function (data) {
debugAlert("appKeyService async method response")
deffered.resolve(data);
});
return deffered.promise;
};
return service;
});

express.JS .push cousing array to be undefined

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 = []

Categories