app.service('customersService', function ($http) {
this.getCustomer = function (id) {
$http({
method: 'GET',
url: '/getCustomer',
params: {id: id},
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
}).success(function(data) {
console.log(data);
return data;
})
};
});
Cannot get the data in the controller from the service
The problem with this code is when i try to run this
customersService.getCustomer(customerID).then
It generates an error mentioned below:
angular.js:13294 TypeError: Cannot read property 'then' of undefined.
The main thing is the call to the service is generated and if i try to print the results on the console in the service the data is there. However i cannot get the data in my controller.
You get that error becuase you are not returning the promise from $http GET request.
Edit your code like this:
app.service('customersService', function ($http) {
this.getCustomer = function (id) {
return $http({
method: 'GET',
url: '/getCustomer',
params: {id: id},
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
});
};
});
And then with .then() in your controller, you handle the response data.
app.controller('myController', function($scope, customerService){
customersService.getCustomer(customerID)
.then(function(response){
$scope.data = response;
})
})
You simply forget to return the $http promise that is why undefined is returned. You need to do the following:
...
return $http({ ...
Try given code.
app.service('customersService', function ($http) {
var getCustomer = function (id) {
return $http({
method: 'GET',
url: '/getCustomer',
params: {id: id},
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
})
};
var customersService = {
getCustomer: getCustomer
}
return ProfileService;
});
Related
I want to make an $http request making use of the configuration object instead of the quick method. The request is of 'GET' method and the url targets a local json file.
The code looks more or less like:
$http.get({
method: 'GET',
url: 'data.json'
}).then(function(res) {
$scope.data = res;
}, function(res) {
console.log(res);
})
The error I get is :
Error: [$http:badreq]
Here's a 'working' plunker demonstrating the problem.
The fact is that if I use the quick method $http.get('clients.json') it works.
Any help would be appreciated.
update your app.js file
var app = angular.module('app', []);
app.controller('MainCtrl', function($scope, $http) {
$http({
url: 'data.json',
type: 'GET'
}).then(function(res) {
$scope.data = JSON.stringify(res.data);
}, function(res) {
console.log(res);
})
});
DEMO
try this it works for me : plunker
app.controller('MainCtrl', function($scope, $http) {
$http({method: 'GET',url : './data.json'}).then(function(res) {
$scope.data = res;
}, function(res) {
console.log(res);
})
});
First on your index.html, you had {data}} instead of :
<body ng-controller="MainCtrl">
{{data}}
</body>
On your controller you have to invoke the $http as following (not using $http.getbut just $http) :
$http({
method: 'GET',
url: 'data.json'
}).then(function successCallback(response) {
$scope.data = response.data;
}, function errorCallback(response) {
console.log(response);
});
See working update here https://plnkr.co/edit/OCPkPYsbcHv2snef5Bj3?p=preview
Seems your code is wrong, you already use $http.get, but still add {method: 'GET'}.
I guess you want to use $http request directly.
$http({
method: 'GET',
url: 'data.json'
}).then(function(res) {
$scope.data = res;
}, function(res) {
console.log(res);
})
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;
});
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 get the response from Service in below case??
Service:
app.factory('ajaxService', function($http) {
updateTodoDetail: function(postDetail){
$http({
method: "POST",
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
url: post_url,
data: $.param({detail: postDetail})
})
.success(function(response){
//return response;
});
}
})
Controller:
updated_details = 'xyz';
ajaxService.updateTodoDetail(updated_details);
In th above case, i POST the data through Controller and it was working fine but now i want the response to come in my Controller.
How to achive that??
$http returns a promise:
Return the promise
updateTodoDetail: function(postDetail){
return $http({
method: "POST",
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
url: post_url,
data: $.param({detail: postDetail})
});
So you can do
ajaxService.updateTodoDetail(updated_details).success(function(result) {
$scope.result = result //or whatever else.
}
Alternatively you can pass the successfunction into updateTodoDetail:
updateTodoDetail: function(postDetail, callback){
$http({
method: "POST",
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
url: post_url,
data: $.param({detail: postDetail})
})
.success(callback);
So your controller has
ajaxService.updateTodoDetail(updated_details, function(result) {
$scope.result = result //or whatever else.
})
I would prefer the first option so I could handle errors etc as well without passing in those functions too.
(NB: I haven't tested the code above so it might require some modification)
what I usually do is like this
app.factory('call', ['$http', function($http) {
//this is the key, as you can see I put the 'callBackFunc' as parameter
function postOrder(dataArray,callBackFunc) {
$http({
method: 'POST',
url: 'example.com',
data: dataArray
}).
success(function(data) {
//this is the key
callBackFunc(data);
}).
error(function(data, response) {
console.log(response + " " + data);
});
}
return {
postOrder:postOrder
}
}]);
then in my controller I just call this
$scope.postOrder = function() {
call.getOrder($scope.data, function(data) {
console.log(data);
}
}
do not forget to insert the dependency injection of 'call' services into your controller
I want create 1 service where i can POST the data and on success i can again GET the data and update the $scope.variable??
How to do that?
I've tried this way:
angular.module('mvc')
.factory('ajaxService', function($http) {
return {
getAjaxData: function(response) {
$http.get(url).success(response);
return response;
},
postAjaxdata: function(postData){
$http({
method: "post",
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
url: url,
data: data
})
.success(function(response){
ajaxService.getAjaxData(function(response) {
$scope.foo = response;
});
});
}
}
});
Capture this in postAjaxdata() to be used in the success callback to call getAjaxData().
You don't have access to the scope inside of the service (nor do you want to access it from a service). The Angular convention is to return a promise to the controller so that it can apply the response value to the scope when the promise is resolved. You can also do this using callbacks (to be consistent with the code that was posted). Here, I've added a callback to postAjaxdata()...
angular.module('mvc')
.factory('ajaxService', function($http) {
return {
getAjaxData: function(successCallback) {
$http.get(url).success(successCallback);
return successCallback;
},
postAjaxdata: function(postData, successCallback){
var that = this;
$http({
method: "post",
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
url: url,
data: data
})
.success(function(){
that.getAjaxData(successCallback);
});
}
}
});
The controller should look something like this...
function controller ($scope, ajaxService) {
// ...
ajaxService.postAjaxdata(postData, function (response) {
$scope.foo = response;
});
}
The main issue is that you can't set scope variables in the way you attempted to from the service.
You could instead use the $q service to return a promise which, when resolved, is set to your $scope.foo variable:
.factory('ajaxService', function($http, $q) {
var ajaxService = {
getAjaxData: function() {
return $http.get(url);
},
postAjaxdata: function(postData){
var deferred = $q.defer();
$http({
method: "post",
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
url: url,
data: postData
})
.success(function(){
deferred.resolve(ajaxService.getAjaxData());
});
return deferred.promise;
}
};
return ajaxService;
});
You'll also notice that I set the body of your factory to a named variable, which you can then use to call functions internally (as you did with ajaxService.getAjaxData()) before returning.
Then, in your controller, you could set your scope variable like this:
.controller('MyController', function($scope, ajaxService){
ajaxService.postAjaxdata().then(function(results){
$scope.foo = results.data;
})
})
Working Plunker
Note: my answer is not entirely dissimilar to Anthony Chu's. I noticed that he posted his just before mine, but I went ahead anyway since mine takes a slightly different approach, utilizing promises instead of callbacks.