I have an AngularJS app which communicates with a REST API. Sending a POST request to my api and in return { logged: false, username: undefined, id: undefined }
if the user is not logged in, otherwise, it will return something like { logged: true, username: 'admin', id: 123 }
.
I want these functions implemented in such a way that calling one will set the values for all the rest. I am getting post response in return , but I am quite confused about checking the condition.
Here is the service I have tried putting together:
app.factory('Authentication', function($http,session){
var service = {};
service.login = function(username,password) {
return $http
.post('http://localhost:3000/loginfo',{
username : username,
password : password
})
.then(
function successCallback(response){
session.create(response.data.id,response.data.username);
return response.data;
});
};
service.isAuthenticated = function() {
return !!session.username;
};
return service;
});
/*-----Main Controller-----*/
app.controller('credientials',['$scope','$route','$http','Authentication',function($scope,$route,$http,Authentication) {
$scope.isAuthenticated = false;
$scope.userCred = {
username: '',
password: ''
}
/*-----Form Submition-----*/
$scope.log = function(userCred){
Authentication.login(userCred.username,userCred.password)
.then(function(result){
console.log(result);
})
.catch(function(err){
console.error(err);
});
Please don't tell me to google it, because I already have so many blue links. If you know anything , please correct me and if you have any working example share it .
Use a promise service $q
in factory
app.factory('Authentication', function($http,$q,session){
var service = {};
service.login = function(username,password) {
return $q(function(resolve, reject) {
$http
.post('http://localhost:3000/loginfo',{
username : username,
password : password
})
.then(function successCallback(response){
session.create(response.data.id,response.data.username);
resolve(response.data);
}, function(err){
reject(err);
});
});
};
service.isAuthenticated = function() {
return !!session.username;
};
return service;
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.