Angular 1.5 - passing http post response to controller - angularjs

I am trying to pass an http response from my controller to a service, it works well except for getting the response to go into the controller here is my code below:
For my service
app.factory('ApiService',function($http,Config,$q){
return {
login: function(payload,callBack){
var deferred = $q.defer();
$http({
method:'POST',
url:Config.baseUrl + '/api/login',
data:payload,
headers: {'Content-Type': 'application/json'},
}).then(function successCallback(callBack){
console.log(callBack);
return deferred.resolve(callBack);
}, function errorCallback(callBack){
//deferred.reject(error);
console.log(callBack);
return deferred.reject(callBack);
});
return deferred.promise;
}
}
});
and for the Controller
app.controller('LoginCtrl', function($scope,$position,$rootScope,$state,ApiService) {
$scope.forms = {
'loginForm':''
}
var payload ={
'username':'',
'password':''
}
$scope.userLogin = function(form){
$scope.username = form.username.$modelValue;
$scope.password = form.password.$modelValue;
payload ={
"username":$scope.username,
"password":$scope.password
}
ApiService.login(payload, function(result){
console.log(result);
}
});
Now I don't understand because when I console.log() the response I'm able to see it in the service but doing the same on the controller I'm getting nothing.

No need to make it complex. Simply return promise from factory and use it in controller.
factory:
app.factory('ApiService',function($http,Config,$q) {
return {
login: function(payload) {
return $http({
method:'POST',
url:Config.baseUrl + '/api/login',
data:payload,
headers: {'Content-Type': 'application/json'},
});
}
}
});
in controller :
ApiService.login(payload).then(function(data){
// use response data
}, function(error) {
// handle error
});

You should use it like this:
ApiService.login(payload).then(function(result){
console.log(result);
});
Because you are returning a promise in your service.
Also you don't need that callback parameter, because the then method on the promise is your callback when it finishes and you can access the data your resolve it with.
app.factory('ApiService',function($http,Config,$q){
return {
login: function(payload){
var deferred = $q.defer();
$http({
method:'POST',
url:Config.baseUrl + '/api/login',
data:payload,
headers: {'Content-Type': 'application/json'},
}).then(function (result){
return deferred.resolve(result);
}, function (result){
return deferred.reject(result);
});
return deferred.promise;
}
}
});

Related

View not loading new data after http request in angularjs

I want to submit data from a form and display the result in the view directly after http request returns a result. But it's not happening.
$scope.formData = {};
$scope.add = function (){
$http.post('add.php',$scope.formData,{'Content-Type': 'application/x-www-form-urlencoded'})
.then(function (result) {
console.log(result.data);
if (result){
$scope.data = result.data;
}
});
};
And this is add.php. In this file I just want to return the posted data in json.
function index(){
$data = $this->input->post();
echo json_encode($data);
}
I find it returns false value. I wonder how I process data submitted with post method using $http.post like this.
You can try this way to pass data to add.php service
$scope.add = function (){
$http({
method: 'POST',
url: 'add.php',
headers: {
'Content-Type': application/x-www-form-urlencoded
},
data:$scope.formData
}).then(function successCallback(response) {
$scope.data = response.data.data;
}, function errorCallback(response) {
console.log(response);
});
}
Try this in PHP:
$data = $this->input->post(NULL, TRUE);
In AngularJS, inject $httpParamSerializerJQLike in your service/factory
$scope.add = function (){
$http({
method: 'POST',
url: '/add.php',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
data: $httpParamSerializerJQLike($scope.formData);
}).then(function resolve(response) {
console.log(response);
$scope.data = response.data.data;
}, function reject(response) {
console.log(response);
});
}

why i get $$State variable with a service angularjs

i want to get just my service in the variable from my controller but it give me an $$state object
this is my controller
$scope.myDataSMS = ServiceSms.async().then(function(data){
$scope.myDataSMS1 = data;
console.log($scope.myDataSMS1);
return $scope.myDataSMS1;
});
console.log($scope.myDataSMS);
and my service
routeAppControllers.factory('ServiceSms', function($http,Token) {
var key = Token.CreateToken()
var myService = {
async: function() {
var data = 'token=' + encodeURIComponent(key);
var promise = $http({
method: 'POST',
url: 'PhpFunction/getsms.php',
data: data,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})
.then(function(data) {
// The then function here is an opportunity to modify the response
// console.log(data.data);
// The return value gets picked up by the then in the controller.
return data.data;
})
// Return the promise to the controller
return promise;
}
};
return myService;
});
i think that the problems is with the promise but there i m little bit stuck
if someone can help me please
thanks in advance
this would be a better way to write your promise:
CONTROLLER:
.controller('nameofcontroller', ['$scope', 'ServiceSms', function($scope, ServiceSms) {
$scope.myDataSMS = ServiceSms.async()
.then(
function(data){
$scope.myDataSMS1 = data;
console.log($scope.myDataSMS1);
return $scope.myDataSMS1;
},
function(err){
console.log('err: ' + err);
});
}]);
SERVICE:
routeAppControllers.factory('ServiceSms', function($http,Token) {
return {
async: function() {
var data = 'token=' + encodeURIComponent(key);
return $http({
method: 'POST',
url: 'PhpFunction/getsms.php',
data: data,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
});
}
}
});

Angular $http called from service, 'then' is undefined

I have seen this question many times but I can't figure out why one of my controller functions (controller 1) works fine and one (controller 2) doesn't.
Controller 1:
angular.module('app').controller('MyCtrl1',function($scope,MyFactory)) {
//This function works great
MyFactory.deleteItem(item.id).then(function(response) {
//woot woot I am here and I am fine
});
}); //end controller 1
Controller 2:
angular.module('app').controller('MyCtrl2',function($scope,MyFactory)) {
//Function #2 that doesn't work ... 'then' is undefined
MyFactory.createItem(item).then(function(response) {
//booo hooo I never get here and I am definitely not fine
});
}); //end controller 2
The factory:
.factory("MyFactory", function($http) {
var service = [];
service.deleteItem = function(itemId) {
return $http({
method: "delete",
url: "http://www.example.com",
params: //valid params go here
}).then(function(response) {
console.log("DELETING!!!!");
return response.data;
});
}
service.createItem = function(post) {
return $http({
url: '?create',
method: 'post',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: payload //an object
}).then(function(response){
console.log(response.data); //we are fine here. there is a valid response
return response.data;
});
}
return service;
}); //end factory
The error thrown when executing 'createItem' is 'Cannot read property 'then' of undefined' What am I missing ?
You are missing the return in the createItem statement:
service.createItem = function(post) {
return $http({
url: '?create',
method: 'post',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: payload //an object
}).then(function(response){
console.log(response.data); //we are fine here. there is a valid response
return response.data;
});
}
Without it, there is no return value (which is undefined) on which you can't chain the .then.
If you are not returning $http the use like this :
$http({
url: '?create',
method: 'post',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: payload //an object
}).$promise.then(function(response){
console.log(response.data);
return response.data;
});

Factory doesnt return http data response

Im trying to get http post data response using the code below (it is working).
app.factory('LoginService', function($http, $location) {
return {
existUser: function(loginObj)
{
$http({
method: 'POST',
url: server + '/login',
headers: {'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'},
data: 'json=' + JSON.stringify(loginObj)
}).then(function successCallback(response) {
return response.data;
}, function errorCallback(response) {
console.log(response);
console.log("erro!");
});
}
}
});
Inside of my controller, i have:
LoginService.existUser(loginObj).then(function (data){
console.log(data);
});
And i got the error:
Cannot read property 'then' of undefined
What is wrong?
Your return response.data; returns result of then function, not existUser! Modify your code like below:
app.factory('LoginService', function($http, $location) {
return {
existUser: function(loginObj)
{
return $http({
method: 'POST',
url: server + '/login',
headers: {'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'},
data: 'json=' + JSON.stringify(loginObj)
})
}
}
});
In this case, existUser method returns promise object, that has .then method

How to do error handling when fetching data in angularjs service

This code fetches categories and give them to controller.
sampleApp.factory('SCService', function($http, $q) {
var SuperCategories = [];
var SCService = {};
SCService.GetSuperCategories = function() {
var req = {
method: 'POST',
url: SuperCategoryURL,
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
data: "action=GET"
};
if ( SuperCategories.length == 0 ) {
return $http(req).then(function (response) {
SuperCategories = response.data;
return SuperCategories;
});
}else {
return $q.when(SuperCategories);
}
}
return SCService;
});
I think code is perfect until there is no error in http request.
My query is how to do error handling (try catch or something like that), in case if server have some issue or may be cgi-script have some issue and not able to server the request.
Angular promises use a method catch for that.
return $http(req).then(function (response) {
SuperCategories = response.data;
return SuperCategories;
}).catch(function(error) {
// Do what you want here
});
You should use also finally :
return $http(req).then(function (response) {
SuperCategories = response.data;
return SuperCategories;
}).catch(function(error) {
// Do what you want here
}).finally(function() {
// Always executed. Clean up variables, call a callback, etc...
});
Write like
return $http(req).then(function (response) {
//success callback
},
function(){
//Failure callback
});
Use callback methods from controller Like
Controller.js
service.GetSuperCategories(function (data) {console.log('success'},function (error){console.log('error'});
service.js
sampleApp.factory('SCService', function($http, $q) {
var SuperCategories = [];
var SCService = {};
SCService.GetSuperCategories = function(successMethod,errorMethod) {
var req = {
method: 'POST',
url: SuperCategoryURL,
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
data: "action=GET"
};
return $http(req).then(successMethod(data),
errorMethod(error));
}
return SCService;
});
You can use the .success and .error methods of $http service, as below
$http(req).success(function(data, status, headers){
// success callback: Enters if status = 200
}).error(function(status, headers){
// error callback: enters otherwise
});

Resources