$http:badreq - GET json Object - angularjs

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

Related

Angular - Pass input value to factory $http query parameter

I have created a factory to run an $http GET method. I need to add an input value to the URL pulling in the JSON but I'm having trouble passing it from the controller. I can see that the URL is being created correctly, I am just missing the "query" parameter from the form input field.
Here is my HTML block:
<input type="string" class="form-control" ng-model="getMovie.title">
Here is my factory and controller:
var app = angular.module('app', []);
app.factory("getMovie", ['$http',function($http){
var obj = {};
var url = "https://api.nytimes.com/svc/movies/v2/reviews/search.json";
obj.getMovieInfo = function(){
return $http({
url: url,
method: "GET",
params:{
query: this.title, // This is the value I need
api_key: "68094e1974e7984c256beb1653319915:3:33678189",
callback: "JSON_CALLBACK"
},
headers: {
"Content-Type" : "application/json"
}
}).then(function successCallback(response) {
this.movieReviews = response.data.results;
}, function errorCallback(response) {
console.log("Nothing to see here...");
});
}
return obj;
}]);
app.controller('moviesCtrl', ["$scope", "getMovie", function($scope, getMovie){
$scope.findMovie = function(){
getMovie.getMovieInfo().then(function(response){
$scope.results = response;
});
}
}]);
Thanks!
You can send the title as parameter to the factory method.
<input type="string" class="form-control" ng-model="title">
var app = angular.module('app', []);
app.factory("getMovie", ['$http',function($http){
var obj = {};
var url = "https://api.nytimes.com/svc/movies/v2/reviews/search.json";
obj.getMovieInfo = function(title){
return $http({
url: url,
method: "GET",
params:{
query: title, // This is the value I need
api_key: "68094e1974e7984c256beb1653319915:3:33678189",
callback: "JSON_CALLBACK"
},
headers: {
"Content-Type" : "application/json"
}
}).then(function successCallback(response) {
this.movieReviews = response.data.results;
}, function errorCallback(response) {
console.log("Nothing to see here...");
});
}
return obj;
}]);
app.controller('moviesCtrl', ["$scope", "getMovie", function($scope, getMovie){
$scope.findMovie = function() {
getMovie.getMovieInfo($scope.title).then(function(response){
$scope.results = response;
});
}
}]);
I recommend you dont use this . If you want use controllerAs syntax , use like this . You can see more in here
https://github.com/johnpapa/angular-styleguide/tree/master/a1#controllers
app.factory("getMovie", ['$http',function($http){
var vm = this
vm.getMovie ={};
And in ajax
return $http({
url: url,
method: "GET",
params:{
query: vm.getMovie, // This is the value I need
api_key: "68094e1974e7984c256beb1653319915:3:33678189",
callback: "JSON_CALLBACK"
},
headers: {
"Content-Type" : "application/json"
}
}).then(function successCallback(response) {
vm.movieReviews = response.data.results;
}, function errorCallback(response) {
console.log("Nothing to see here...");
});
}
return obj;
}]);

How to make $resource.post call without sending data

I have done this using $http.post as below:
$http({
method: 'POST',
url: 'www.someurl'+myid
}).then(function successCallback(response) {
console.log(response)
}, function errorCallback(response) {
console.log(response)
});
Requirement is to make the same post call using $resource. I tried as below:
filter:
saffModuleServices.factory('Projects', ['$http', '$resource', '$appConstants',
function ($http, $resource, $appConstants) {
$http.defaults.useXDomain = true;
delete $http.defaults.headers.common['X-Requested-With'];
var createDraftEndPoint=www.someurl/:id;
var saveEmailDraftEndPoint=www.someurl.com
return {
saveEmailDraft: function(){
return $resource(saveEmailDraftEndPoint, {}, {
update: {method: 'PUT', params: {},headers: {'Content-Type':'application/json'}}
});
},
createDraft: function(){
return $resource(createDraftEndPoint, {}, {
post: {method: 'POST',param{id:''}}
});
},
}
}]);
controller:
saffModuleControllers.controller('ctrl', ['$scope', 'SaffNotification','Projects','$filter',
function ($scope, Notification,Projects,$filter) {
Projects.createDraft().post({id:myid}, function(response){
Notification.success({message: $filter('translate')('administration_item_save_notification'), templateUrl: 'common/templates/toastr_success_template.html'});
}, function(response){
Notification.error({message: response.data.errorMessage, templateUrl: 'common/templates/toastr_error_template.html'});
});
}]);
error:
myId is going as data for this request, but I want to send that as param and no data should be sent. I could do that using $http.post
Can anyone suggest me how to make this request in $resource.post without editing $httpProvider in config, because I dont want to make 'data' parameter nil for other POST request.

Cannot get the data in the controller from the service

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

$http POST & $http GET in 1 service

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.

http get request using angularjs

So I am trying to send Get request with angularjs
However I am getting this error
Error: Argument 'SimpleController' is not a function, got undefined
here is my code
var module = angular.module('myApp', []);
module.config(function ($httpProvider) {
$httpProvider.defaults.headers.post['SOAPAction'] = 'http://schemas.microsoft.com/sharepoint/soap/UpdateListItems';
});
function SimpleController($scope,$http)
{
$http({
url: "http://localhost:8080/petstore/pets/list",
method: "GET",
})
.success(function(data){
console.log("SUCCESS");
$scope.pets = data;
}).error(function() {
console.log("FAIL");
console.log("data: "+data+"\nstatus: "+status+"\nheaders: "+headers+"\nconfig: "+config)
$scope.pets = [ {"id":1,"name":"Angelfish","description":"Saltwater fish from Australia","category":"Fish","imageUrl":"fish1.jpg","price":10}];
});
}
Instead of
function SimpleController($scope,$http)...
try using
module.controller('SimpleController',function($scope,$http){
// function body
});
It looks like you have an extra comma causing the invalid function:
$http({
url: "http://localhost:8080/petstore/pets/list",
method: "GET", // <--- remove that comma
})

Resources