AngularJS $http REST call returns null data - json

I have a REST service that returns a JSON object. I am trying to make the authentication but it responses with empty data.
I did notice that the call is asychronous and when the user is pressing the login button it makes the call before getting the username and password. So I decided to use the $q constructor in order to fix it, but the problem consists, it still returns null data.
What am I doing wrong?
Thanks in advance.
factory
angular.module('myApp', ['ngRoute'])
.factory('User', ['$http', '$q', function($http, $q) {
return {
login: function(username, password) {
var deferred = $q.defer();
$http.post('http://localhost:8080/CashInRestServices_war/rest/user/login', {username: username, password: password})
.then (function(data, status, headers, config){
deferred.resolve(data);
}, function(data, status, headers, config) {
deferred.reject(data);
})
return deferred.promise;
}
}
}])
controller
.controller('MainCtrl', ['$scope', 'User', function($scope, User) {
$scope.username = "viewer";
$scope.password = "viewer";
$scope.login = function() {
User.login($scope.username ,$scope.password)
.then(function(response) {
console.log("success!");
$scope.status = response.status;
$scope.data = response.data;
$scope.username = response.username;
alert("Success!!! " + JSON.stringify({data: response.data}));
}, function (response) {
$scope.data = response.data || "Request failed";
$scope.status = response.status;
console.log("Error!!!");
alert( "failure message: " + JSON.stringify({data: response.data}));
})
};
}])
*****EDIT*****
I did change the code a little bit. I think the problem was how the $http was written.
factory
angular.module('myApp', ['ngRoute'])
.factory('User', ['$http', function($http) {
return {
login: function(username, password) {
return $http({method:'post', url: 'http://localhost:8080/CashInRestServices_war/rest/user/login', username: username, password: password})
}
}
}])
It did somehow worked but it returns loginCheck:false. It seems that it does not recognize the correct username and password.
response = Object {data: Object, status: 200, config: Object, statusText: "OK"}
log:
Object {data: Object, status: 200, config: Object, statusText: "OK"}config: Objectheaders: Objectmethod:
"POST"paramSerializer: (b)password: "viewer"transformRequest: Array[1]transformResponse: Array[1]url: "http://localhost:8080/CashInRestServices_war/rest/user/login"username: "viewer"__proto__: Objectdata: ObjectloginCheck: false__proto__:
Objectheaders: (c)arguments: (...)caller: (...)length: 1name: ""prototype: Objectconstructor: (c)__proto__: Object__proto__: ()<function scope>ClosureClosureGlobal: Windowstatus: 200statusText: "OK"__proto__: Object__defineGetter__: __defineGetter__()__defineSetter__: __defineSetter__()__lookupGetter__: __lookupGetter__()__lookupSetter__: __lookupSetter__()
constructor: Object()hasOwnProperty: hasOwnProperty()isPrototypeOf: isPrototypeOf()propertyIsEnumerable: propertyIsEnumerable()toLocaleString: toLocaleString()toString: toString()valueOf: valueOf()get __proto__: get __proto__()set __proto__: set __proto__()

I figured it out. The login function was causing the problem $scope.login = function() so I used the $event object.
html
<div><button ng-click="login($event)" type="submit">Login</button></div>
factory
angular.module('myApp', ['ngRoute'])
.factory('User', ['$http', function($http) {
return {
login: function(username, password) {
// return $http({method:'post', url: 'http://localhost:8080/CashInRestServices_war/rest/user/login', username: username, password: password})
var data = {username: username,password: password};
console.log(JSON.stringify(data));
return $http({
method:'post',
url: 'http://localhost:8080/CashInRestServices_war/rest/user/login',
data: JSON.stringify(data),
headers: {'Content-Type': 'application/json'}
})
}
}
}])
controller
.controller('MainCtrl', ['$scope', 'User', function($scope, User) {
$scope.username = "viewer";
$scope.password = "viewer";
$scope.login = function(event) {
event.preventDefault();
User.login($scope.username ,$scope.password)
.then(function(response) {
$scope.status = response.status;
$scope.data = response.data;
alert(JSON.stringify({data: response.data}));
}, function (response) {
$scope.data = response.data || "Request failed";
$scope.status = response.status;
alert( "failure message: " + JSON.stringify({data: response.data}));
})
};
}])

$http service is already returning a promise, so return it directly without using all the plumber :
login: function(username, password) {
return $http.post('http://localhost:8080/CashInRestServices_war/rest/user/login', {username: username, password: username});
}
}

Try like this, anyway if you can show us your console log.
angular.module('myApp', ['ngRoute'])
.factory('User', ['$http', function($http) {
return {
login: function(username, password) {
var myUrl = 'http://localhost:8080/CashInRestServices_war/rest/user/login';
var data = {
username: username,
password: password
};
return $http({
url: myUrl,
method: 'POST',
data: JSON.stringify(data),
headers: {
'Content-Type': 'application/json'
}
}).then(function(response) {
return response;
});
}
}
}])
Change your controller like this:
.controller('MainCtrl', ['$scope', 'User', function($scope, User) {
$scope.username = "viewer";
$scope.password = "viewer";
$scope.login = login;
////////////////////
function login() {
User.login($scope.username ,$scope.password)
.then(function(response) {
$scope.status = response.status;
$scope.data = response.data;
$scope.username = response.data.username; // I dont know if response.data.username exists but i am sure that response.username doesn't
}
};
}])

Related

receiving a json response with vue.js2 in laravel

sending a request and getting response which bases on it i want to chege the status and display something different, can't figure out what's the problem, the route seems to be working fine and I'm receiving a response which looks like this
I'm trying to access this using Vue component and I'm getting that error status is not defined, here is my Vue component
<script>
export default {
mounted() {
axios.get('/userfound/' + this.profile_user_id)
.then(function (response) {
console.log(response);
this.status = response.data.status;
})
.catch(function (error) {
console.log(error);
});
},
props: ['profile_user_id'],
data(){
return {
status: ''
}
},
methods:{
add_friend(){
// this.loading = false
axios.get('/add_friend/' + this.profile_user_id)
.then(function (response) {
console.log(response);
if (response.data == 1) {
this.status = 'waiting'
}
})
.catch(function (error) {
console.log(error);
});
}
}
}
</script>
why am i getting this error: TypeError: cannot read property 'status' of undefined ..
i've tried "this.status = response.body.status" and "this.status = response.data.status" but neither is working
I believe there is an issue with the scope of a variable. Try below answer:
<script>
export default {
mounted() {
var self = this;
axios.get('/userfound/' + self.profile_user_id)
.then(function (response) {
console.log(response);
self.status = response.data.status;
})
.catch(function (error) {
console.log(error);
});
},
props: ['profile_user_id'],
data(){
return {
status: ''
}
},
methods:{
add_friend(){
// you can do same here as well
var self = this;
axios.get('/add_friend/' + self.profile_user_id)
.then(function (response) {
console.log(response);
if (response.data == 1) {
self.status = 'waiting'
}
})
.catch(function (error) {
console.log(error);
});
}
}
}
</script>

HTTP request with angularJS

I'm trying to make an HTTP request from AngularJS v1.5.8 but it does not work.
I have a simple HTML form and a submit button that calls my login() function:
<body ng-app="myApp" ng-controller="loginController">
......
......
......
<div
class="col-md-4 col-md-offset-4 col-sm-4 col-sm-offset-3 col-xs-6 col-xs-offset-3">
<button type="submit" class="btn btn-default" ng-submit="login()">Submit</button>
</div>
And this is my loginController
var app = angular.module ("myApp", []);
app.controller("loginController", function($scope, $http){
$scope.username = "";
$scope.password = "";
$scope.login = function() {
$http(
{
method : 'POST',
url : SessionService.getserverName()+'/RestServices/services/login/add',
headers : {
'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8'
},
data : {
username : $scope.username,
password : $scope.password
}
}).success(function(response, status) {
if (response.result.success && status == 200) {
$log.info('OK');
$location.path('/newPage.html');
}
})
}
});
The HTTP request does not really run.
ngSubmit attribute work only on form element. see https://docs.angularjs.org/api/ng/directive/ngSubmit.
Try to move
ng-submit="login()"
to your form element
Try with using the structure below ..
$http({
url: 'put url here',
method: "put action here just like GET/POST",
data: { 'name': 'Rizwan Jamal' }
})
.then(function (resp) {
//TODO: put success logic here
},
function (resp) {
//TODO: put failed logic here
}
);
.then() method fires in both the success and failure cases. The then() method takes two arguments a success and an error callback which will be called with a response object.
NOTE :
If you are not using form validation so please change ng-submit with ng-click.. I hope this solution will work for You :)
app.js
'use strict';
// Declare app level module which depends on filters, and services
var app= angular.module('myApp', ['ngRoute','angularUtils.directives.dirPagination','ngLoadingSpinner']);
app.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/login', {templateUrl: 'partials/login.html', controller: 'loginCtrl'});
$routeProvider.when('/home', {templateUrl: 'partials/home.html', controller: 'homeCtrl'});
$routeProvider.when('/salesnew', {templateUrl: 'partials/salesnew.html', controller: 'salesnewCtrl'});
$routeProvider.when('/salesview', {templateUrl: 'partials/salesview.html', controller: 'salesviewCtrl'});
$routeProvider.when('/users', {templateUrl: 'partials/users.html', controller: 'usersCtrl'});
$routeProvider.when('/forgot', {templateUrl: 'partials/forgot.html', controller: 'forgotCtrl'});
$routeProvider.otherwise({redirectTo: '/login'});
}]);
app.run(function($rootScope, $location, loginService){
var routespermission=['/home']; //route that require login
var salesnew=['/salesnew'];
var salesview=['/salesview'];
var users=['/users'];
$rootScope.$on('$routeChangeStart', function(){
if( routespermission.indexOf($location.path()) !=-1
|| salesview.indexOf($location.path()) !=-1
|| salesnew.indexOf($location.path()) !=-1
|| users.indexOf($location.path()) !=-1)
{
var connected=loginService.islogged();
connected.then(function(msg){
if(!msg.data)
{
$location.path('/login');
}
});
}
});
});
loginServices.js
'use strict';
app.factory('loginService',function($http, $location, sessionService){
return{
login:function(data,scope){
var $promise=$http.post('data/user.php',data); //send data to user.php
$promise.then(function(msg){
var uid=msg.data;
if(uid){
scope.msgtxt='Correct information';
sessionService.set('uid',uid);
$location.path('/home');
}
else {
scope.msgtxt='incorrect information';
$location.path('/login');
}
});
},
logout:function(){
sessionService.destroy('uid');
$location.path('/login');
},
islogged:function(){
var $checkSessionServer=$http.post('data/check_session.php');
return $checkSessionServer;
/*
if(sessionService.get('user')) return true;
else return false;
*/
}
}
});
sessionServices.js
'use strict';
app.factory('sessionService', ['$http', function($http){
return{
set:function(key,value){
return sessionStorage.setItem(key,value);
},
get:function(key){
return sessionStorage.getItem(key);
},
destroy:function(key){
$http.post('data/destroy_session.php');
return sessionStorage.removeItem(key);
}
};
}])
loginCtrl.js
'use strict';
app.controller('loginCtrl', ['$scope','loginService', function ($scope,loginService) {
$scope.msgtxt='';
$scope.login=function(data){
loginService.login(data,$scope); //call login service
};
}]);

How to call jsonp api using $http in angularjs

// this is service where i m calling api
app.factory('users',['$http','$q', function($http , $q) {
return {
getUsers: function() {
var deferred = $q.defer();
var url = 'http://www.geognos.com/api/en/countries/info/all.jsonp?callback=JSONP_CALLBACK';
$http.jsonp(url).success(function (data, status, headers, config) {
console.log(data);
deferred.resolve(data);
}).
error(function (data, status, headers, config) {
//this always gets called
console.log(status);
deferred.reject(status);
});
return deferred.promise;
}
}
}]);
//this is my controller where i calling getUsers();
app.controller('myCtrl', function($scope, users) {
$scope.data = users.getUsers();
})
while calling it gives me error
Uncaught ReferenceError: callback is not defined(anonymous function)
Plz give me proper solution so that i can see me api data in <div>. Thanks in advance
$http already returns a promise. There is no need to form a promise of a promise. Try this:
app.factory('Users', ["$http", function($http){
return {
getUsers: function(url) {
return $http({
url: url,
method: 'JSONP'
});
}
};
}]);
Controller:
app.controller("MyCtrl", ["$scope", "Users", function($scope, Users) {
$scope.data = [];
Users.getUsers('http://www.geognos.com/api/en/countries/info/all.jsonp?callback=JSONP_CALLBACK').then(function(response){
console.log(response.data);
$scope.data = response.data;
}).catch(function(response){
console.log(response.statusText);
});
}]);
Here the scenario is a bit different as you have to declare a $window.callback function.
Code
var app = angular.module("demoApp", []);
app.factory('UserService', ['$http', function ($http, $q) {
var getUsers = function () {
var url = 'http://www.geognos.com/api/en/countries/info/all.jsonp?callback=callback';
return $http.jsonp(url);
};
return {
GetUsers: getUsers
}
}]);
app.controller("demoController",
["$scope", "$window", "UserService",
function ($scope, $window, UserService){
UserService.GetUsers();
$window.callback = function (response) {
$scope.countries = response.Results;
}
}]);
Plunkr: http://plnkr.co/edit/MFVpj1sMqJpcDg3ZwQFb?p=preview

why it's appending #/... in location.hash

I am using angular js for my app.
Here , My Angular code as :
var app = angular.module('TaskManager', ['ngCookies']);
app.controller('LoginController', function($scope, $http, $location, $cookieStore) {
$scope.login = function(str) {
console.log(".......... login called......");
$http({
method: 'POST',
url: '../TaskManager/public/user/login',
data: $.param({
email: email.value,
password: password.value
}),
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
})
.success(function(data, status) {
console.log(data);
var result = data.response;
console.log(result);
if (result == "success") {
//storing value at cookieStore
$cookieStore.put("loggedin", "true");
$cookieStore.put("loggedUserId", data.user_id);
$cookieStore.put("password", data.password);
$cookieStore.put("type", data.type);
$cookieStore.put("email", data.email);
location.href='Dashboard.html';
} else alert(data.message);
});
});
app.controller('DashboardController', function($scope, $http, $location, $cookieStore) {
$scope.users = [];
$http({
method: 'POST',
url: '../TaskManager/public/task/tasklist',
data: $.param({
logged_userid: userId,
password: password,
status: 'All',
user_id: useridToFetch
}),
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
})
.success(function(data, status) {
console.log(data);
$scope.users = data.users;
});
//location.hash="";
console.log(window.location);
});
It works fine but when it redirects to the dashboard page after logged in, the location.hash is being assigned with the #/PAGE_NAME. it becomes location.hash=#/PAGE_NAMEwhich results the URL value repetition.
Like:
http://localhost:8085/NovaTaskManager/Dashboard.html#/Dashboard.html
I tried to clear hash at DashboardController, Which clears for a while but as soon as the page is refreshed the earlier URL appears again.
Don't know:
1. why location.hash is getting assigned by default ?
2. How it can be resolved ?
Any suggestion would be appreciated.

Using return $q.when in Hot Towel Angular datacontext

I've created a web application using the Hot Towel Angular template, and I want to add a service function to the 'datacontext'.
Code is:
(function () {
'use strict';
var serviceId = 'datacontext';
angular.module('app').factory(serviceId, ['common', '$http', datacontext]);
function datacontext(common, $http) {
var $q = common.$q;
var service = {
getFunctions: getFunctions
};
return service;
function getFunctions() {
var f = [];
$http({
method: 'GET',
url: 'https://api.github.com/users/google/repos',
contentType: 'application/json; charset=utf-8'
})
.success(function (data, status, headers, config) {
f = data;
console.log('f=*' + f + '*');
})
.error(function (data, status, headers, config) {
alert('error!');
});
return $q.when(f);
}
}
})();
I see that the console shows some objects:
f=*[object Object],[object Object],[object O...
But when using this in my functionController.js file :
function getFunctions() {
return datacontext.getFunctions().then(function (data) {
console.log('data=*' + data + '*');
return vm.functions = data;
});
}
The value for data is set to undefined.
I'm missing something, please help identify the error.
Solution:
The getFunctions function in the datacontext should return the $http promise object, like this:
function getFunctions() {
return $http.get('https://api.github.com/users/google/repos')
.error(function (data, status, headers, config) {
alert('error ! : ' + status);
});
}
And in the controller, you can use the returned json object as follows:
function getRepos() {
return datacontext.getRepos().then(function (httpResult) {
vm.repos = httpResult.data;
});
}