I'm new to angular and I've been told that it's better to make services do the heavy lifting for the controllers, but I'm finding it diffcult to make use of the services I've created. I've seen several questions on this but I can't find solutions.
Here's my service
(function () {
'use strict';
var office = angular.module('Office', []);
office.factory('auth', ['$http', '$localForage', '$scope', function ($http, $localForage, $scope) {
var auth = {}
auth.login = function (credentials) {
$http.post('/auth_api/login', credentials)
.then(function (data) {
$localForage.setItem('user', data.data)
},
function () {
$scope.login_error = 'Invalid Username/password'
})
}
$localForage.getItem('user').then(function (data) {
auth.isAuthenticated = !!data.id
})
return auth
}])
And here's my controller
office.controller('LoginController', ['$scope', 'auth', function ($scope, auth) {
$scope.login = auth.login($scope.user)
}])
I have created a simpler version from your code.. and its working here . check the link - fiddle
app.factory('auth', ['$http', function ($http) {
var auth = {};
auth.login = function (credentials) {
return "success";
}
return auth;
}]);
replace login function with your implemenation
Your code is correct but as you are not returning anything from the "auth" factory, you are not getting any update in the controller. Change your code as shown below to return the data from factory or any message acknowledging the login.
Factory :
(function () {
'use strict';
var office = angular.module('Office', []);
office.factory('auth', ['$http', '$localForage', '$scope', function ($http, $localForage, $scope) {
var auth = {}
auth.login = function (credentials) {
return $http.post('/auth_api/login', credentials)
.then(function (data) {
$localForage.setItem('user', data.data);
setAuthentication(true);
return data.data;
},
function (err) {
return err;
});
}
auth.setAuthentication = function (isLoggedIn){
this.isAuthenticated = isLoggedIn;
}
return auth;
}]);
Controller :
office.controller('LoginController', ['$scope', 'auth', function ($scope, auth) {
$scope.login = function (){
auth.login($scope.user).then(function (data){
$scope.userDetails = data;
}, function (err){
$scope.loginError = 'Invalid Username/password';
});
}
}]);
Related
I am trying to call a factory function from the controller .
My code:
angular.module("mainApp", ['ui.router', 'ngAnimate', 'toaster'])
.factory("authenticationSvc", function($http, $q, $window) {
var userInfo;
function login(userName, password) {
var deferred = $q.defer();
$http.post("/api/login", {
userName: userName,
password: password
}).then(function(result) {
userInfo = {
accessToken: result.data.access_token,
userName: result.data.userName
};
$window.sessionStorage["userInfo"] = JSON.stringify(userInfo);
deferred.resolve(userInfo);
}, function(error) {
deferred.reject(error);
});
return deferred.promise;
}
return {
login: login
};
})
.controller("LoginController", function($scope, toaster, $rootScope, $stateParams, $location, $http, authenticationSvc) {
$scope.login = authenticationSvc.login();
});
But I am getting an error
TypeError: authenticationSvc.login is not a function
The function login needs two parameter
So the function login without a parameter isn't definded
Firstly, the approach and formalization of factory is not done properly.
try using the following approach..
.factory("authenticationSvc", function($http, $q, $window) {
var userInfo;
var authenticationSvc={};
//Define login()
authenticationSvc.login=function(userName, password) {
var deferred = $q.defer();
$http.post("/api/login", {
userName: userName,
password: password
}).then(function(result) {
userInfo = {
accessToken: result.data.access_token,
userName: result.data.userName
};
$window.sessionStorage["userInfo"] = JSON.stringify(userInfo);
deferred.resolve(userInfo);
}, function(error) {
deferred.reject(error);
});
return deferred.promise;
}
//return Factory Object
return authenticationSvc;
})
And in the controller , try calling in the same approach
.controller("LoginController", function($scope, toaster, $rootScope, $stateParams, $location, $http, authenticationSvc) {
$scope.login = authenticationSvc.login();
});
Hope this helps.
Cheers
Here below is the basic example that how factories are behaving. Please change your code with below one
angular.module("mainApp", ['ui.router', 'ngAnimate', 'toaster'])
.factory("authenticationSvc", function($http, $q, $window) {
var userInfo, authentication = {};
authentication.login = function(userName, password) {
var deferred = $q.defer();
$http.post("/api/login", {
userName: userName,
password: password
}).then(function(result) {
userInfo = {
accessToken: result.data.access_token,
userName: result.data.userName
};
$window.sessionStorage["userInfo"] = JSON.stringify(userInfo);
deferred.resolve(userInfo);
}, function(error) {
deferred.reject(error);
});
return deferred.promise;
}
return authentication;
})
.controller("LoginController", function($scope, toaster, $rootScope, $stateParams, $location, $http, authenticationSvc) {
$scope.login = authenticationSvc.login(user,password);
});
Please check though I didn't test it. Inside in your factory :
You just create an object, add properties to it, then return that same
object. When you pass this service into your controller, those
properties on the object will now be available in that controller
through your factory.
So I'm trying to retrieve a token from the server but I'm encountering an error when trying to call a method in my service.
LoginController.js:
(function(){
angular.module('app')
.controller('LoginController', [
'$http', 'authService',
LoginController
]);
function LoginController(authService ) {
var vm = this;
vm.user = {};
vm.login = function () {
console.log("logging in");
authService.getToken("admin", "admin")
.then(function (data) {
console.log(data);
}, function (error) {
//TODO: error handling
})
};
}
})();
authService.js:
(function(){
'use strict';
angular
.module('app')
.factory('authService', ['$http', '$rootScope', 'REST_END_POINT',
authService
]);
function authService($http, $rootScope, REST_END_POINT){
return {
getToken: function(username, password) {
var config = {
headers: {
'Accept': 'application/json'
}
};
var data = {
username: login,
password: password
};
return $http.post(REST_END_POINT, +"/authenticate", data, config);
}
};
}
})();
I keep getting this error :
TypeError: authService.getToken is not a function
at LoginController.vm.login
You forgot to add $http to your controller function.
angular.module('app')
.controller('LoginController', [
'$http', 'authService',
LoginController
]);
function LoginController(_$http_needs_to_be_here, authService ) {
...
Remove $http from this line since you have it injected in your service already
angular.module('app')
.controller('LoginController', [
'authService',
LoginController
]);
You have wrong no of params in LoginController function. You have request angular to inject $http and authService. But you have only one param in function. For more info pls read Angular DI
Re-write code:
(function(){
angular.module('app')
.controller('LoginController', [
'$http', 'authService',
LoginController
]);
function LoginController($http, authService ) {
var vm = this;
vm.user = {};
vm.login = function () {
console.log("logging in");
authService.getToken("admin", "admin")
.then(function (data) {
console.log(data);
}, function (error) {
//TODO: error handling
})
};
}
})();
i have my authservice as given below ,
myApp.factory('Authentication',
['$rootScope', '$location', 'URL', '$http', '$q',
function ($rootScope, $location, URL, $http, $q) {
var myObject = {
authwithpwd: function (user) {
var dfd = $q.defer();
$http
.post('Mart2/users/login', {email: user.email, password: user.password})
.then(function (res) {
return dfd.resolve(res.data);
}, function (err) {
return dfd.reject(err.data);
});
return dfd.promise;
} //login
};
return myObject;
}]); //factory
And i'm using that service in user service as follows :
myApp.factory('UserService',
['$rootScope', '$location', 'URL', '$http', '$q', 'Authentication',
function ($rootScope, $location, URL, $http, $q, $Authentication) {
var myObject = {
login: function (user) {
$Authentication.authwithpwd(user).then(function (regUser) {
console.log(regUser);
}).catch(function (error) {
$rootScope.message = error.message;
});
},
getUserToken: function () {
return $rootScope.currentUser.apiKey;
},
isLogged: function () {
if ($rootScope.currentUser) {
return true;
} else {
return false;
}
}
//login
};
return myObject;
}]); //factory
I am very new to angular js . While writing service and calling that service from controller i have put a console debug in user service which is showing its returning object .i am getting object if i do console.log(regUser) ? any idea why ?
To get the object you need to do change your myObject declaration. Basically you need to return a promise from the login function and then write a callback to get the resolved data.
myApp.factory('UserService',
['$rootScope', '$location', 'URL','$http','$q','Authentication',
function($rootScope,$location, URL,$http,$q,$Authentication) {
var myObject = {
login: function(user) {
var defer = $q.defer();
$Authentication.authwithpwd(user).then(function(regUser) {
console.log(regUser);
defer.resolve(regUser);
}).catch(function(error) {
$rootScope.message = error.message;
defer.reject(regUser);
});
return defer.promise;
},
getUserToken:function() {
return $rootScope.currentUser.apiKey;
},
isLogged:function() {
if($rootScope.currentUser){
return true;
} else {
return false;
}
}//login
};
return myObject;
}]); //factory
To extract the object from controller or from some other service you need to write a callback
UserService.login(user)
.then(function (data) {
$scope.data = data;
}, function (error) {
$scope.error = error;
});
Also in the Authentication service you can just do a 'dfd.resolve' instead of 'return dfd.resolve'; since you are already returning the dfd.promise.
I have created a fiddler here
I'm trying to get a value from a URL part, into my $http getURL request. I have tried a few solutions (such as HTML5mode) but have not had success.
Here is my code:
angular.module('myapp123.products', [])
.factory('productsApi', ['$http', '$location',
function($http, $location){
var BASE_URL = 'http://stashdapp-t51va1o0.cloudapp.net/api/item/';
return {
get: getApiData
};
function getData() {
var product_id = $location.path().split("/")[3] || "Unknown"; //URL = /#/product/id/1234 <---
return $http.get(BASE_URL + product_id);
}
}]
)
.controller('productsCtrl', ['$scope', '$log', 'productsApi', 'UserService',
function($scope, $log, productsApi, UserService) {
$scope.isVisible = function(name){
return true;// return false to hide this artist's albums
};
// <====== Rewrite with accounts preferences
productsApi.getApiData()
.then(function (result) {
//console.log(JSON.stringify(result.data)) //Shows log of API incoming
$scope.products = result.data;
})
.catch(function (err) {
$log.error(err);
});
}
]);
The code in your example has a lot of syntax errors in it. Here is what it should look like, based on what I think you are going for...
angular.module('myapp123.products', [])
.config(locationConfig)
.factory('productsApi', productsApiFactory)
;
locationConfig.$inject = ['$locationProvider'];
function locationConfig($locationProvider) {
$locationProvider.html5Mode(true);
}
productsApiFactory.$inject = ['$http', '$location'];
function productsApiFactory($http, $location) {
var BASE_URL = 'http://stashdapp-t51va1o0.cloudapp.net/api/list/';
return {
get: getData
};
function getData() {
var product_id = $location.path().split("/")[3] || "Unknown";
return $http.get(BASE_URL + product_id);
}
}
In this version, the config function is correctly defined to set up html5mode and the service factory is configured to use $location each time the get() method is called.
You would use the service in a controller like this:
ExampleController.$inject = ['productsApi'];
function ExampleController(productsApi) {
productsApi.get()
.then(function onSuccess(res) {
// handle successful API call
})
.catch(function onError(err) {
// handle failed API call
})
;
}
I would like to store the value from /api/login.json globally using a service, but I think I have some sort of timing issue. The console.log statement in the controller tells me that the scope.login object is undefined.
What am I missing?
Thanks!
Factory service:
myApp.factory('LoginFactory', ['$http', function($http){
this.data;
$http.get('/api/login.json').success(function(data) {
this.data = data;
});
return {
getData : function(){
return this.data;
}
}
}]);
Controller:
myApp.controller('AccountsCtrl', ['$scope', 'Accounts', 'LoginFactory', function($scope, Accounts, LoginFactory){
$scope.login = LoginFactory.getData();
console.log('$scope.login: %o', $scope.login);
$scope.accounts = Accounts.index();
}]);
you should probably avoid use of the this keyword in this context. better just to declare a new variable.
myApp.factory('LoginFactory', ['$http', function ($http) {
var data;
$http.get('/api/login.json').success(function (d) {
data = d;
});
return {
getData: function () {
return data;
}
};
}]);
you will still have a race issue though, so i would also recommend either promise chaining
myApp.factory('LoginFactory', ['$http', function ($http) {
var promise = $http.get('/api/login.json');
return {
getData: function (callback) {
promise.success(callback);
}
};
}]);
or even a conditional get
myApp.factory('LoginFactory', ['$http', function ($http) {
var data;
return {
getData: function (callback) {
if(data) {
callback(data);
} else {
$http.get('/api/login.json').success(function(d) {
callback(data = d);
});
}
}
};
}]);
The last two approaches require you to rewrite your controller though
myApp.controller('AccountsCtrl', ['$scope', 'Accounts', 'LoginFactory', function($scope, Accounts, LoginFactory){
LoginFactory.getData(function(data) {
$scope.login = data;
console.log('$scope.login: %o', $scope.login);
$scope.accounts = Accounts.index(); //this might have to go here idk
});
}]);
Extending #LoganMurphy answer. Using promise and still adding callbacks is not at all desirable. A better way of writing service could be
myApp.factory('LoginFactory', ['$http', function ($http, $q) {
var data;
return {
getData: function () {
if(data) {
return $q.when(data);
} else {
return $http.get('/api/login.json').then(function(response){
data = response;
return data;
});
}
}
};
}]);
You have an issue with the this keyword and also you not handling the promise from the http.get correctly
I would write it like this:
myApp.factory('LoginFactory', ['$http', function($http){
return {
getData : function(){
return $http.get('/api/login.json');
}
}
}]);
myApp.controller('AccountsCtrl', ['$scope', 'Accounts', 'LoginFactory', function($scope, Accounts, LoginFactory){
$scope.login = LoginFactory.getData().success(function(data){
console.log(data);
console.log('$scope.login: %o', $scope.login);
});
}]);