Pass authentication error from factory to controller in AngularJS - angularjs

I am trying to implement Firebase authentication via a factory and I would like to pass the error and even the authData object back to the controller from the factory. Is this possible? I can't seem to figure out how. I keep getting undefined variables.
If I print the error upon a failed login to console.log I get what should be expected, so the rest of this code works. I just can't pass the error/obj back to the controller.
My controller:
myApp.controller('LoginController', ['$scope', '$location', 'Authentication', function($scope, $location, Authentication) {
$scope.login = function() {
Authentication.login($scope.user);
// do something with error from auth factory
}
}]);
My factory:
myApp.factory('Authentication', ['$firebase', 'FIREBASE_URL', '$location', function($firebase, FIREBASE_URL, $location){
var ref = new Firebase(FIREBASE_URL);
var authObj = {
login: function(user) {
return ref.authWithPassword({
email : user.email,
password : user.password
}, function(error, authData) {
if (error) {
// pass error back to controller
// i've tried the following:
// authObj.err = error;
// return authObj.err = error;
}
else {
// pass authData back to controller
}
});
} // login
};
return authObj;
}]);

You simply pass an error handler function to the factory from the controller. Something like this (untested):
//Controller
myApp.controller('LoginController', ['$scope', '$location', 'Authentication', function($scope, $location, Authentication) {
$scope.login = function() {
Authentication.login($scope.user, function(error, authData) {
// access to error
});
}
}]);
//Factory
myApp.factory('Authentication', ['$firebase', 'FIREBASE_URL', '$location', function($firebase, FIREBASE_URL, $location){
var ref = new Firebase(FIREBASE_URL);
var authObj = {
login: function(user, errorHandler) {
return ref.authWithPassword({
email : user.email,
password : user.password
}, errorHandler);
} // login
};
return authObj;
}]);

Maybe you can do this in your controller:
$scope.login = function() {
Authentication.login(username, password).then(
function(result) {
$location.path('/stuff');
},
function(result) {
$scope.showLoginErrorMessage = true;
});
};
Note that then() takes 2 functions as parameters (one for success and one for error). This does depend on how your Authentication service works, but it looks OK to me.

Related

Angularjs Factoryname.function is not a function

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.

Can't access service in controller

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

Promise returning object in angular js

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

Running factory based on condition

I have a log in screen that when the user enters the correct credentials will be able to get JSON data. For now I don't have a real API link. I'm just using dummy JSON data from a script file. The loginCtrl will pass parameters to the 'dummydata' factory which will make a 'GET' request. On success, the factor will pass the JSON data to the 'useData' function in the factory. This function in the factory is what all the controllers in my ng-view use.
The problem that I am having is that all the other controllers are calling 'dummyData.dashboardsData' and getting undefined because no one has logged in to pass data to that function. How can I prevent controllers (for example, navCtrl) from calling the factory until someone has logged in?
This is my index file:
<body ng-app="ciscoImaDashboardApp" ng-style="{'background-image': backgroundImg}" ng-controller="loginCtrl">
<login></login>
<div ng-view></div>
<menu></menu>
</body>
This is my factory:
angular.module('ciscoImaDashboardApp').factory('dummyData', ['$q', '$http', function($q, $http) {
var apiServices = {};
apiServices.login = function(user,password,callback) {
$http({method: 'GET', url: 'scripts/services/dummydata.js'})
.success(function (response) {
dataStatus = response.success;
apiServices.useData(response);
callback(dataStatus);
})
.error(function(error) {
console.log("There was an error: " + error);
});
};
apiServices.useData = function(response) {
var data = response.data;
apiServices.dashboardsData = data;
}
return apiServices;
}]);
This is my navCtrl:
angular.module('ciscoImaDashboardApp')
.controller('navCtrl', function($scope, navService, $location, dummyData) {
var data = dummyData.dashboardsData;
});
This is my loginCtrl:
angular.module('ciscoImaDashboardApp')
.controller('loginCtrl', function ($scope, $rootScope, dummyData, $location) {
$scope.login = function() {
var user_email = $scope.email;
var user_password = $scope.password;
dummyData.login(user_email, user_password, function (dataStatus) {
if (dataStatus) {
console.log("Success!");
$scope.loggedIn = true;
$location.path('/welcome');
} else {
console.log("Error");
}
});
}
});

handle asynchronous behavior firebase in angularjs

I'm trying put the authentication of my firebase in a service. But I stumbled on some problems with program flow. The response from firebase is slower and the code needs to wait for it to complete.
I tried to create a promise, but it doesnt work properly.
Here is my code:
//controller.js
articleControllers.controller('AuthController',
['$scope', '$firebaseObject', 'AuthenticationService',
function($scope, $firebaseObject, AuthenticationService){
$scope.login = function() {
AuthenticationService.login($scope.loginForm)
.then(function(result) {
if(result.error) {
$scope.message= result.error.message;
}
else {
console.log("user");
}
});
};
}
]);
services.js
myApp.factory('AuthenticationService',
function($firebase, $firebaseAuth, $routeParams, FIREBASE_URL) {
var auth = new Firebase(FIREBASE_URL);
var myReturnObject = {
//user login
login: function(user) {
return auth.authWithPassword({
email: user.loginEmail,
password: user.loginPassword
},
function(error, authData) {
console.log("hit after .then");
return {
error: error,
authData: authData
}
});
}
};
return myReturnObject;
});
I already used a promise once in my code for a $http get request. But for firebase it doesnt seem to work. I get the error: Cannot read property 'then' of undefined in controller.js.
Anyone an idea how I can let angular wait for the service?
remember to inject $q.
myApp.factory('AuthenticationService',
function($q, $firebase, $firebaseAuth, $routeParams, FIREBASE_URL) {
var auth = new Firebase(FIREBASE_URL);
var myReturnObject = {
//user login
login: function(user) {
return $q(function(resolve, reject) {
auth.authWithPassword({
email: user.loginEmail,
password: user.loginPassword
}, function authCallback(error, authData) {
if (error) {
return reject(error);
}
resolve(authData);
});
});
}
};
return myReturnObject;
});

Resources