passing multiple value from js page to php page - javascript

I want to multiple value from from serice page to php page.I want to pass 'data','albimg','albvideo' to php page.now I caught the error as shown in image.
var deferred = $q.defer();
data.pagename = "create_album";
$http.post('js/data/album.php', {action:{"data":data,"albimg":albimg,"albvideo":albvideo}})
.success(function (data, status, headers, config)
{
console.log(status + ' - ' + action);
deferred.resolve(action);
})
.error(function (action, status, headers, config)
{
deferred.reject(action);
console.log('error');
});
return deferred.promise;
php page:
$postdata = file_get_contents("php://input",true);
$request = json_decode($postdata);
$now = date('Y-m-d H:i:s');
echo $sql="INSERT INTO `$prefix.album` (CONTENT_VALUES,CreatedTime)VALUES('$postdata','$now')";

you can do it by using param property: like this;
var data = {"data":data,"albimg":albimg,"albvideo":albvideo};
$http({ url: "js/data/album.php", method: "POST", params: data })

There is no action param defined in success callback.
Your code
.success(function (data, status, headers, config) // No Action here
{
console.log(status + ' - ' + action); // This line gives error
deferred.resolve(action);
})
Should be
.success(function (data, status, headers, config, action) // Add Action here
{
console.log(status + ' - ' + action);
deferred.resolve(action);
})

Look to this example:
function PhoneListCtrl($scope, phones) {
$scope.phones = phones;
$scope.orderProp = 'age';
}
PhoneListCtrl.resolve = {
phones: function(Phone, $q) {
var deferred = $q.defer();
deferred.reject();
Phone.query(function(successData) {
deferred.resolve(successData);
}, function(errorData) {
deferred.reject();
});
return deferred.promise;
},
delay: function($q, $defer) {
var delay = $q.defer();
$defer(delay.resolve, 1000);
return delay.promise;
}
}
I think that you forget add $defer to your function. Do you realy need asynchronously? Beacouse if you use $q it's that you need it. But if you just want to send data to php file easiest way to use something like this:
angular.module('httpExample', [])
.controller('FetchController', ['$scope', '$http', '$templateCache',
function($scope, $http, $templateCache) {
$scope.method = 'Post';
$scope.url = 'http-hello.php';
$scope.fetch = function() {
$scope.code = null;
$scope.response = null;
$http({method: $scope.method, url: $scope.url, cache: $templateCache}).
then(function(response) {
$scope.status = response.status;
$scope.data = response.data;
}, function(response) {
$scope.data = response.data || "Request failed";
$scope.status = response.status;
});
};
$scope.updateModel = function(method, url) {
$scope.method = method;
$scope.url = url;
};
}]);

Related

AngularJS $http.post/service issue

I have a weird problem.. when I am loading my details page, the error part gets executed first in the controller.
Though the service myService gets executed and it does return value, in the controller error is executed and I am not getting my message details.
I have put an alert in service before and jsonObj is valid.
controller:
url = 'http://' + add + ':8080/user/site.cgi';
data = {
ACTION : "list",
STATS : "no"
};
myService.getdata(url, data)
.then(function(data, status, headers, config) {
$timeout(function(){
if (data.body.response.status == "OK") {
if (data.body.response.msg.id) {
service2.seturl(data.body.response.msg.id, username, add);
messg.push(data.body.response.msg);
} else
angular.forEach(data.body.response.msg, function(value, key) {
service2.seturl(value.id, username, add);
messg.push(value);
})
$rootScope.messg = messg;
} else {
errorMessage = data.body.response.errmsg;
alert(errorMessage);
}
}, 5000);
}, function(error, status, headers, config) {
alert("Check network connection.."); //Coming here without fulfilling promise.
});
}
services:
.service('myService', function($http, $q, $httpParamSerializerJQLike) {
return {
getdata: function(url, data) {
var postData = data;
return $http({
method : 'POST',
url : url,
data : $httpParamSerializerJQLike(postData)
}).then(function(response, status, headers, config) {
var x2js = new X2JS();
var jsonObj = x2js.xml_str2json(response.data);
if (typeof jsonObj === 'object') {
alert(jsonObj); //I am getting this alert just fine.
return jsonObj; //It does return the object.
} else {
return $q.reject(jsonObj);
}
}, function(response, status, headers, config) {
return $q.reject(response.data);
});
}
}
})
.factory('service2', function() {
var urls = [{ }];
return {
all: function() {
return urls;
},
geturl: function(id) {
for (var i = 0; i < urls.length; i++) {
if (urls[i].id === parseInt(id)) {
return urls[i];
}
}
return null;
},
seturl: function(id, admin, add) {
for (var i = 0; i < urls.length; i++) {
if (urls[i].id === parseInt(id)) {
return null;
}
}
var idInt = parseInt(id);
var createurl = 'http://' + add + ':8080/user/det.cgi';
var postData = {
ACTION : “add”,
LOGIN : admin
};
var url = {
id: idInt,
url: createurl,
data: postData
}
urls.push(url);
return null;
}
};
})
Try this , return a deferred promise
.service('myService', function($http, $q, $httpParamSerializerJQLike) {
return {
getdata: function(url, data) {
var deferred = $q.defer();
var postData = data;
$http({
method : 'POST',
url : url,
data : $httpParamSerializerJQLike(postData)
}).then(function(response, status, headers, config) {
var x2js = new X2JS();
var jsonObj = x2js.xml_str2json(response.data);
if (typeof jsonObj === 'object') {
alert(jsonObj);
deferred.resolve(jsonObj);
} else {
deferred.reject(jsonObj);
}
}, function(response, status, headers, config) {
deferred.reject(response.data);
});
return deferred.promise;
}
}
})

How do I avoid a function expression when trying to return a local variable within an AngularJS factory?

How do I return "stories" by issuing "vm.stories = storyDataAsFactory.stories" vs. what I do now, which is "vm.stories = storyDataAsFactory.stories()" ? I've tried every combination possible without success. Furthemore, I'm able to call storyDataAsFactory.getStories without the parenthesis, which makes sense based on how I have it configured, but when I create a function that returns self.stories it doesn't work.
The below code works as specified -
storyDataAsFactory.$inject = ['$http', '$q'];
angular.module('ccsApp').factory('storyDataAsFactory', storyDataAsFactory);
function storyDataAsFactory($http, $q) {
var self = this;
var stories = [];
function getStories(url) {
url = url || '';
var deferred = $q.defer();
$http({method: 'GET', url: url})
.success(function (data, status, headers, config) {
self.stories = data;
deferred.resolve(data);
})
.error(function (data, status, headers, config) {
deferred.reject(status);
});
return deferred.promise;
}
function listStories() {
return self.stories;
}
return {
stories: listStories,
getStories: getStories('stories.json')
};
}
UPDATE:
I'm still having problems. Here's my exact code, which I changed per the community -
storyDataAsFactory.$inject = ['$http', '$q'];
angular.module('ccsApp').factory('storyDataAsFactory', storyDataAsFactory);
function storyDataAsFactory($http, $q) {
var stories = [];
function getStories(url) {
url = url || '';
if (url !== '') {
var deferred = $q.defer();
//determine if ajax call already occurred;
//if so, data exists in cache as local var
if (stories.length !== 0) {
deferred.resolve();
return deferred.promise;
}
$http({method:'GET', url:url})
.success(function (data, status, headers, config) {
stories = data;
deferred.resolve();
})
.error(function (data, status, headers, config) {
deferred.reject(status);
});
return deferred.promise;
} else {
alert('URL was empty.');
}
}
return {
stories: stories,
getStories: function(url) {
getStories(url);
}
};
}
storyDataAsFactory.stories does not return anything. Remember, I've ensued that resolve fired appropriately so this is not an async. issue. I just don't get this! I've been at it for hours w/o success.
I think you are confused with Angular service and factory concept:
Lets dicuss below:
Angular service:
module.service( 'serviceName', function );
Result: When declaring serviceName as an injectable argument you will be provided
with the instance of a function passed to module.service.
Angular factory
module.factory( 'factoryName', function );
Result: When declaring factoryName as an injectable argument you will be provided
the value that is returned by invoking the function reference passed to
module.factory. So if you want to access the methods of that factory then
they should be there along with returned value.
Angular's service version of your given code will be:
schoolCtrl.service('storyDataAsService', storyDataAsService);
function storyDataAsService($http, $q) {
var self = this;
var stories = [];
this.getStories = function(url) {
url = url || '';
var deferred = $q.defer();
$http({method: 'GET', url: url})
.success(function (data, status, headers, config) {
self.stories = data;
deferred.resolve(data);
})
.error(function (data, status, headers, config) {
deferred.reject(status);
});
return deferred.promise;
};
this.stories = function(){
// #TODO return value
}
}
Angular's factory version:
storyDataAsFactory.$inject = ['$http', '$q'];
angular.module('ccsApp').factory('storyDataAsFactory', storyDataAsFactory);
function storyDataAsFactory($http, $q) {
var self = this;
var stories = [];
function getStories(url) {
url = url || '';
var deferred = $q.defer();
$http({method: 'GET', url: url})
.success(function (data, status, headers, config) {
self.stories = data;
deferred.resolve(data);
})
.error(function (data, status, headers, config) {
deferred.reject(status);
});
return deferred.promise;
}
return {
stories: function() {
// #TODO return value
},
getStories: getStories
};
}
In your case self is provider of your factory storyDataAsFactoryProvider. But you need use local variable stroies, not provider object field self.stroies. I have fixed your bugs. Now it works.
UPD: if you want to use stories as field instead of getter you cannot change local variable (reference to original array). You may modify original array only.
storyDataAsFactory.$inject = ['$http', '$q'];
angular.module('ccsApp', /*XXX added []*/[]).factory('storyDataAsFactory', storyDataAsFactory);
function storyDataAsFactory($http, $q) {
var stories = [];
function getStories(url) {
url = url || '';
if (url !== '') {
var deferred = $q.defer();
//determine if ajax call already occurred;
//if so, data exists in cache as local var
if (stories.length !== 0) {
deferred.resolve();
return deferred.promise;
}
$http({method:'GET', url:url})
.success(function (data, status, headers, config) {
// XXX using this code you lose original array
//stories = data;
// XXX instead you need to clear and to fill original array
stories.splice(0, stories.length);
data.forEach(function(x) { stories.push(x); });
deferred.resolve();
})
.error(function (data, status, headers, config) {
deferred.reject(status);
});
return deferred.promise;
} else {
alert('URL was empty.');
}
}
return {
stories: stories, // XXX using field instead of getter you need to keep original array
getStories: function(url) {
getStories(url);
}
};
}
// ------------ tests --------------------
describe('storyDataAsFactory.stories()', function() {
var $httpBackend, $http, $q, storyDataAsFactory;
beforeEach(module('ccsApp'));
beforeEach(inject(function(_$httpBackend_) {
$httpBackend = _$httpBackend_;
$httpBackend.whenGET('stories.json').respond([1, 2, 3]);
}));
beforeEach(inject(function(_$http_, _$q_, _storyDataAsFactory_) {
$http = _$http_;
$q = _$q_;
storyDataAsFactory = _storyDataAsFactory_;
}));
it('should return empty array before ajax resolved', function() {
storyDataAsFactory.getStories('stories.json');
expect(storyDataAsFactory.stories).toEqual([]);
$httpBackend.flush();
});
it('should return filled array after ajax resolved', function() {
storyDataAsFactory.getStories('stories.json');
$httpBackend.flush();
expect(storyDataAsFactory.stories).toEqual([1, 2, 3]);
});
});
// ------------ run tests --------------------
window.onload = function() {
var jasmineEnv = jasmine.getEnv();
var htmlReporter = new jasmine.HtmlReporter();
jasmineEnv.addReporter(htmlReporter);
jasmineEnv.execute();
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/jasmine/1.3.1/jasmine.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/jasmine/1.3.1/jasmine.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jasmine/1.3.1/jasmine-html.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.28/angular-mocks.js"></script>

Error: [$injector:unpr] Unknown provider: Learning AngularJS Could use a pointer or two

I am leaning Angular my first application is a photo sharing tool. I added the code for the upload function and broke it. I thought I was defining the albumProvider in my controller, but apperently I have failed to do so. The error is Error: [$injector:unpr] Unknown provider. I am stuck and could us a hand on what I need to fix.
albumService.js
(function () {
function albumProvider($http,$fileUploader) {
this.getUploader = function (album_name, scope) {
return $fileUploader.create({
scope: scope,
method: "PUT",
url: "/v1/albums/" + album_name + "/photos.json"
});
};
this.getAlbums = function (callback) {
$http.get("/v1/albums.json")
.success(function (data, status, headers, conf) {
callback(null, data);
})
.error(function (data, status, headers, conf) {
callback(data);
});
};
this.getPhotosForAlbum = function (name, callback) {
$http.get("/v1/albums/" + name + "/photos.json")
.success(function (data, status, headers, conf) {
callback(null, data);
})
.error(function (data, status, headers, conf) {
callback(data);
});
};
this.addAlbum = function (album_data, callback) {
if (!album_data.name) return callback({ code: "missing_name" });
if (!album_data.title) return callback({ code: "missing_title" });
if (!album_data.description) return callback({ code: "missing_description" });
if (!album_data.date) return callback({ code: "missing_date" });
if (!is_valid_date(album_data.date)) return callback({ code: "bad_date" });
$http.put("/v1/albums.json", album_data)
.success(function (data, status, headers, conf) {
callback(null, data);
})
.error(function (data, status, headers, conf) {
callback(data);
});
};
}
photoApp.service("albumProvider", albumProvider);
function is_valid_date(the_date) {
if (the_date.match(/^[0-9]{2,4}[\-\/\. ,][0-9]{1,2}[\-\/\. ,][0-9]{1,2}$/)) {
var d = new Date(the_date);
return !isNaN(d.getTime());
} else {
return false;
}
}
})();
albumUploadController.js
(function () {
function AlbumUploadController($scope, $routeParams, albumProvider) {//Dependency Inject albumProvider
$scope.album_name = $routeParams.album_name;
$scope.page_load_error = '';
$scope.description = {};
albumProvider.getPhotosForAlbum($scope.album_name, function (err, photos) {
if (err) {
if (err.error == "not_found")
$scope.page_load_error = "No such album. Are you calling this right?";
else
$scope.page_load_error = "Unexpected error loading page: " + err.code + " " + err.message;
} else {
$scope.photos = photos;
$scope.uploader = albumProvider.getUploader($scope.album_name, $scope);
$scope.uploader.bind("completeall", function (event, items) {
$scope.done_uploading = true;
});
}
});
$scope.uploader.bind('beforeupload', function (event, item) {
var fn = _fix_filename(item.file.name);
var d = item.file.lastModifiedDate;
var dstr = d.getFullYear() + "/" + d.getMonth() + "/" + d.getDate();
item.formData = [{
filename: fn,
date: dstr,
description: $scope.descriptions[item.file.name]
}];
});
}
photoApp.controller("AlbumUploadController", AlbumUploadController);
function _fix_filename(fn) {
if (!fn || fn.length == 0) return "unknown";
var r = new RegExp("^[a-zA-Z0-9\\-_,]+$");
var out = "";
for (var i = 0; i < fn.length; i++) {
if (r.exec(fn[i]) != null)
out += fn[i];
}
if (!out) out = "unknown_" + (new Date()).getTime();
}
})();
app.js
var photoApp = angular.module('photoSharingApp', ['ngRoute']);
photoApp.config(function ($routeProvider) {
$routeProvider
.when("/albums", {
controller: "AlbumListController",
templateUrl: "/app/partial/albumPartial.html"
})
.when("/album/:album_name", {
controller: "AlbumViewController",
templateUrl: "/app/partial/albumViewPartial.html"
})
.when("/album/:album_name/upload", {
controller: "AlbumUploadController",
templateUrl: "/app/partial/albumUploadPartial.html"
})
.when("/album/photos/:album_name/:photo_filename", {
controller: "PhotoViewController",
templateUrl: "/app/partial/photoViewPartial.html"
})
.when("/", {
redirectTo: "/albums"
})
.when("/404_page", {
controller: "Controller404",
templateUrl: "/app/partial/404Partial.html"
})
.otherwise({
redirectTo: "/404_page"
});
});
you need to set up the file uploader in your app configuration like:
var photoApp = angular.module('photoSharingApp', ['ngRoute','angularFileUpload']);
then as far i know you may change your fileuploader definition for:
return new FileUploader({
scope: scope,
method: "PUT",
url: "/v1/albums/" + album_name + "/photos.json"
});
I'm not sure about passing the scope to the service, but you can try that out, also don't forget to update your dependency from $fileUploader to FileUploader

AngularJS issues with injecting a new service into my controller

I have a new userContext.js file which attempts to create a new service entitle "userService". This service in turn will communicate with the server and return some environmental settings, as well as a user session ID.
This all works fine when I call it from my dashboard.js into my datacontext.js controller; however I would like to actually create a service for this. I would then persist those session vars throughout the lifetime of each user session.
In my initial attempt to create the service I am getting lots of injector errors, for example :
Error: [ng:areq] Argument 'fn' is not a function, got string
I have included it in my index.html:
<script src="app/services/userContext.js"></script>
Here's a dashboard controller snippet where I attempt to inject 'userService' :
(function () {
'use strict';
var controllerId = 'dashboard';
angular.module('app').controller(controllerId, ['$scope', '$routeParams', '$location', 'common', 'datacontext', 'userService', dashboard]);
function dashboard($scope, $routeParams, $location, common, datacontext, userService) {
var getLogFn = common.logger.getLogFn;
var log = getLogFn(controllerId);
var vm = this;
getRzInitParams();
function getRzInitParams() {
log('Initializing Server Connection...');
var rzParams = "";
datacontext.getRzInitParams().then(function (data) {
rzParams = data;
initRz(data);
});
}
function initRz(data) {
var response;
datacontext.initRz().then(function (data) {
response = data[0].split(":")
if (response[1].match(/SUCCESS/g)) {
log('Server init returned ' + response[1].match(/SUCCESS/g));
openUserSession();
}
else {
log('Server init failed !');
}
});
}
}
})();
and here's a snippet from datacontext.js :
(function () {
'use strict';
var serviceId = 'datacontext';
angular.module('app').factory(serviceId, ['$http', 'common', datacontext]);
function datacontext($http, common) {
var $q = common.$q;
var service = {
initRz: initRz,
openUserSession: openUserSession,
getRzInitParams: getRzInitParams
};
return service;
function initRz() {
domain = "localhost:"
port = "49479";
controllerpath = "/api/init";
space = "rz64698";
env = "rz64698";
cl_config = "C:\\Rz\\rz64698\\master\\bin\\cl_config.xml";
var url = "http://" + domain + port + controllerpath + "?space=" + space + "&environment=" + env + "&clConfig=" + cl_config;
var deferred = $q.defer();
deferred.notify("Getting init parameters...");
var retval = [];
$http({
method: 'GET',
encoding: 'JSON',
headers: {
'Access-Control-Allow-Origin': 'true'
},
withCredentials: true,
url: url
}).success(function (data, status, headers, config) {
retval = data;
deferred.resolve(retval);
});
return deferred.promise;
}
function getRzInitParams() {
var deferred = $q.defer();
var retval = [];
$http({
method: 'GET',
encoding: 'JSON',
url: 'breeze/breeze/GetRzEnv'
}).success(function (data, status, headers, config) {
retval = data;
deferred.resolve(retval);
});
return deferred.promise;
}
}
})();
and finally the new 'userService' service I am now creating :
(function () {
'use strict';
var app = angular.module('app');
app.service('userService', '$http', function () {
// define private vars
var _rzEnvParams = [];
var _sessionID = '';
this.initrz = function(domain, port, controllerpath, space, env, clariteconfig) {
domain = "localhost:"
port = "49479";
controllerpath = "/api/init";
space = "rz64698";
env = "rz64698";
cl_config = "C:\\rz\\rz64698\\master\\bin\\clarite_config.xml";
var url = "http://" + domain + port + controllerpath + "?space=" + space + "&environment=" + env + "&clariteConfig=" + cl_config;
var deferred = $q.defer();
deferred.notify("Getting Rage init parameters...");
var retval = [];
$http({
method: 'GET',
encoding: 'JSON',
headers: {
'Access-Control-Allow-Origin': 'true'
},
withCredentials: true,
url: url
}).success(function (data, status, headers, config) {
retval = data;
deferred.resolve(retval);
});
return deferred.promise;
}
this.getrzInitParams = function () {
var deferred = $q.defer();
deferred.notify("Getting Rage init parameters...");
var retval = [];
$http({
method: 'GET',
encoding: 'JSON',
url: 'breeze/Rage/GetrzEnv'
}).success(function (data, status, headers, config) {
retval = data;
deferred.resolve(retval);
});
return deferred.promise;
}
this.openUserSession = function() {
domain = "localhost:"
port = "49479";
controllerpath = "/api/open";
user = "";
pass = "";
var url = "http://" + domain + port + controllerpath + "?userid=" + user + "&pass=" + pass;
var deferred = $q.defer();
deferred.notify("Opening user session...");
var retval = [];
$http({
method: 'GET',
encoding: 'JSON',
headers: {
'Access-Control-Allow-Origin': 'true'
},
withCredentials: true,
url: url
}).success(function (data, status, headers, config) {
retval = data;
deferred.resolve(retval);
});
return deferred.promise;
}
this.closeUserSession = function(domain, port, controllerpath) {
}
});
})();
If you want to inject some service you should use one of this syntaxes
if you need only angular services
app.service('userService', function ($http) {
...
if you need custom services
app.service('myService', ['$http', 'myOtherService', function($http, myOtherService) {
...
}])
app.service('userService', '$http', function () {
should be like
app.service('userService', function ($http) {
hope this will work

Expose an object from an Angular service using Getter function return undefined

here is the code:
authServ.getUser() returns {} (an empty object, which corresponds to the declaration of this var), from everywhere, even after the revision that I have made to the return syntax according to this [question][1].
Can anyone please advise what is the issue?, I don't see a reason why it shouldn't work
app.factory('authService', function($http){
var authServ = {};
var currentUser = {};
authServ.authUser = function(){
return $http.head('/users/me', {withCredentials: true});
},
authServ.getUser = function(){
return currentUser;
},
authServ.setCompany = function(companyId){
currentUser.company = companyId;
}
authServ.loadCurrentUser = function(){
$http.get('/users/me', {withCredentials: true}).
success(function(data, status, headers, config){
console.log(data);
currentUser.company = currentUser.company ? currentUser.company : data.main_company;
currentUser.companies = [];
for(var i in data.roles){
currentUser.companies.push(data.roles[i]['company_name']);
if(data.roles[i]['company'] == currentUser.company)
currentUser.role = data.roles[i]['role_type'];
}
console.log(currentUser);
}).
error(function(data, status, headers, config){
currentUser.role = 'guest';
currentUser.company = 1;
});
}
return authServ;
});
WORKING CODE:
run(function($rootScope, $location, $http, authService){
$rootScope.$on("$routeChangeError", function(event, current, previous, rejection){
if(rejection.status == 401)
$location.path('/login');
})
authService.loadCurrentUser().then(function(){
console.log(authService.getUser());
});
});
app.factory('authService', function ($http) {
authServ = {};
that = this;
that.currentUser = {};
authServ.authUser = function () {
return $http.head('/users/me', {
withCredentials: true
});
},
authServ.getUser = function () {
return that.currentUser;
},
authServ.setCompany = function (companyId) {
that.currentUser.company = companyId;
},
authServ.loadCurrentUser = function () {
return $http.get('/users/me', {
withCredentials: true
}).
success(function (data, status, headers, config) {
console.log(data);
that.currentUser.company = that.currentUser.company ? that.currentUser.company : data.main_company;
that.currentUser.companies = [];
for (var i in data.roles) {
that.currentUser.companies.push(data.roles[i]['company_name']);
if (data.roles[i]['company'] == that.currentUser.company) that.currentUser.role = data.roles[i]['role_type'];
}
console.log(that.currentUser);
}).
error(function (data, status, headers, config) {
that.currentUser.role = 'guest';
that.currentUser.company = 1;
});
}
return authServ;
});
Fiddle:
http://jsfiddle.net/V9Ex6/1/
Closure issue. Try
app.factory('authService', function($http){
var authServ = {};
that = this; //that captures the current closure
this.currentUser = {};
authServ.getUser = function(){
return that.currentUser;
},
And change loadCurrentUser to access to the variable using that.currentUser.
Edit:
authService.loadCurrentUser();
console.log(authService.getUser());
The user is not guaranteed to be printed out since loadCurrentUser loads the user asynchronously. You should change loadCurrentUser to take a callback function in order to get the user value.
Hope it helps.
Try this, mind you I haven't tested it :)
app.factory('authService', function($http){
return {
authUser: function(){
return $http.head('/users/me', {withCredentials: true});
},
getUser: function(){
return currentUser;
},
setCompany: function(companyId){
currentUser.company = companyId;
},
loadCurrentUser: function(){
$http.get('/users/me', {withCredentials: true}).
success(function(data, status, headers, config){
console.log(data);
currentUser.company = currentUser.company ? currentUser.company : data.main_company;
currentUser.companies = [];
for(var i in data.roles){
currentUser.companies.push(data.roles[i]['company_name']);
if(data.roles[i]['company'] == currentUser.company)
currentUser.role = data.roles[i]['role_type'];
}
console.log(currentUser);
}).
error(function(data, status, headers, config){
currentUser.role = 'guest';
currentUser.company = 1;
});
}
}
});

Categories