I have been working to write a service to return username.
var username, $promise;
angular.module('TestApp').factory('UserService', function($http) {
$promise= $http.get('/api/getuser')
.success(function(data) {
username = data;
});
$promise.then(function() {
return username;
});
});
But injecting this service in an controller would return in an undefined value
angular.module('TestApp')
.controller('UserLoginController', function($scope, UserService){
console.log("Username is: "+ UserService);
});
I have confirmed that http get request returns valid username value. I am quite new to angular and would really appreciate if anyone can point out what am I doing wrong here.
This code above looks like spaghetti. Here is a basic factory that should do what you want:
app.factory('UserService', [ '$http', function($http){
var userService = {};
userService.getUser = function(){
return $http.get('/api/getuser').then(function(res){
return res.data;
},function(error){
console.log(error);
return [];
});
}
return userService;
}]);
then call it in a controller:
app.controller('MyController', ['$scope', 'UserService', function($scope,UserService){
$scope.user = {};
UserService.getUser().then(function(data){
$scope.user = data.users[0];
});
}]);
This assumes a json format similar to { users: [{ id: "34534534",name: "John" }] }
returned by your API.
Please note that I wrote this on the fly and didn't try it out. It should work though.
Warning: I just edited my code to fix some mistakes.