I try to pass my form parameters to java rest backend but i cant.
controller
$scope.addNewThing = function () {
Myservice.addNew($scope.name);
};
service
addNew: function (name) {
var Foo = $resource($rootScope.baseUrl + '/path/addNew', {}, {
save: {method: 'POST', params: {}}
});
var results = Foo.save({name: name}, function(data) {
results = data;
});
return results;
}
//also tried this version of code
addNew: function(name) {
return $resource($rootScope.baseUrl + '/path/addNew', {}, {
save: {method: 'POST', params: {name: 'test'}}
});
}
rest backend function
#POST
#Produces("application/json")
#Path("/addNew")
public Response addNew(#FormParam("name") String name) {
try {
//when i check name here it is always null
...
}
}
I can't pass the html form parameter to java rest backend via angular. Also tried to change #FormParam to #QueryParam but it didn't work.
Did you set the default content-type on $http POST requests?
app.config(function($httpProvider) {
$httpProvider.defaults.headers.post = {};
$httpProvider.defaults.headers.post["Content-Type"] = "application/json; charset=utf-8";
});
I don'n know how to receive params value in java but I can show how to pass params from angular service. when you will want to pass params then you should use :paramsName in your URL path.
addNew: function(name) {
var addNewItem = $resource($rootScope.baseUrl + '/path/addNew/:name', {name: '#name'}, {
'post': {method: 'GET'}
});
return addNewItem.post({name: name});
}
or if you don't use /:name in your url you should pass in your header
addNew: function(name) {
var addNewItem = $resource($rootScope.baseUrl + '/path/addNew/:name', {}, {
'post': {method: 'GET', headers: { 'name': name }}
});
return addNewItem.post({name: name});
}
NB: your Content-Type should be application/json
You can try this:
CONTROLLER
$scope.addNewThing = function () {
yourService.addNew($scope.name);
};
SERVICE
angular.module('MyApp')
.service('yourService',['$http', function ($http) {
this.addNew = function (data) {
$http({
url: 'YourURL',
method: 'POST',
data: data, // your $scope.name
headers: {'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8'}
})
.success(function (response) {
console.log('good');
})
.error(function (response) {
console.log('error');
});
};
}]);
JAVA REST API
#POST
#Path("/addNew")
#Consumes("*/*")
public Response addNew(String name) {
// use here your String name
}
Using jQuery params solved my problem
Here is the correct way:
Myservice.addNew().save($.param({
name:$scope.name
}),function(data){
console.log(data);
},function(err){
console.log(err);
});
I can pass the parameters like this with $resource service.
Related
Hi there I write a service of $resource for connecting the api.
here is the code in service.js
.factory('selfApi2', function ($resource, localStorageService) {
var AB = {
data: function (apiURL, header, data, params) {
return $resource("http://localhost:4000/api" + apiURL, null, {
update: {
method: 'POST',
headers: header,
data: data,
params: params
}
});
}
};
return AB;
})
in my controller.js
var header = {
'Content-Type': 'application/x-www-form-urlencoded'
};
var myData = {
'phone': '12345678'
};
selfApi2.data('/tableName',header,{where:{"name":"kevin"}).update(myData, function(result){
console.log("update Kevin's phone succeed",result);
})
it works. But why the variable myData should put inside the update() part rather than the data() part?
In your case, the data() is a function which will just create a ReST resource which would expose rest apis get save query remove delete as default.
So in this data() call you are just creating the rest resources. Passing myData with this function would not make any sense. The data() call would return the Resource instance which will have your update api function which accepts the parameters.
And, passing your data at api construction time does not make sense.
Here is the complete reference
I think it's because "data" is a function that returns object of $resource.
Try the scenario below:
// service
.factory('api', function ($resource) {
var api = {};
api.issues = $resource("http://localhost:4000/api/issues");
api.users = $resource("http://localhost:4000/api/users", {}, {
update: {
method: 'PUT',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
},
});
return api;
})
// controller
api.users
.update({where:{name:'kevin'}})
.$promise.then(function(success) {
// DO SOMETHING
});
...
api.issues.query().$promise.then(
function(success) {
// DO SOMETHING
});
I am trying to do a login for my app, using a rest api I designed. If I force the complete URL with the user and the pass It works alright:
http://www.myexample.com/ACTION/USER/PASSWORD/
But I need to take the data from the input fields of my form. This is code of the function in my controller:
$scope.authenticar = function(selectedUs, selectedPw){
$scope.remoteData = null;
//alert(selectedUs);
dataService.getData(function(data) {
$scope.resultAPI = data;
$scope.username=$scope.resultAPI.username;
$scope.id_user=$scope.resultAPI.id_user;
$scope.isauthenticated=$scope.resultAPI.isauthenticated;
$scope.user_role=$scope.resultAPI.user_role;
$scope.complete_name=$scope.resultAPI.complete_name;
});
}
And this is the service code:
.service('dataService', function($http) {
delete $http.defaults.headers.common['X-Requested-With'];
this.getData = function(callback) {
var myparams = {a: '', u: '', p: ''};
myparams.a = 'ZW50cmFy';
myparams.u = 'anRk';
myparams.p = '899960d8dd39b29e790845912cb35d96';
$http({
method: 'GET',
url: 'http://www.adagal.net/api_adagal/api.php',
withCredentials: false,
params: myparams,
headers: {
'Content-Type': 'application/json; charset=utf-8'
}
}).success(function(data, status, header, config){
// With the data succesfully returned, call our callback
callback(data);
}).error(function(){
$scope.remoteData = null;
return "Connection Error";
});
}
});
I tried to pass all the ways, how can I get the URL this way?
Not entirely sure what you are trying to do here, you want to pass username and password by url? or post/get data?
Either way you'll need to pass the username and password into the service. You can do that by passing it in the service function.
this.getData = function(username, password, callback) {
...
})...
}
On the calling side:
dataService.getData($scope.username, $scope.password, function(){...});
If I understood your question correctly, you should change your service like this:
.service('dataService', function($http) {
delete $http.defaults.headers.common['X-Requested-With'];
this.getData = function(URL, callback) {
var myparams = {a: '', u: '', p: ''};
myparams.a = 'ZW50cmFy';
myparams.u = 'anRk';
myparams.p = '899960d8dd39b29e790845912cb35d96';
$http({
method: 'GET',
url: URL,
withCredentials: false,
params: myparams,
headers: {
'Content-Type': 'application/json; charset=utf-8'
}
}).success(function(data, status, header, config){
// With the data succesfully returned, call our callback
callback(data);
}).error(function(){
$scope.remoteData = null;
return "Connection Error";
});
}
});
And then call it like this:
var url = "http://wwwmyexample.com/ACTION/" + $scope.selectedUs + "/" + $scope.selectedPw + "/"
dataService.getData(url, function(data) {
$scope.resultAPI = data;
$scope.username=$scope.resultAPI.username;
$scope.id_user=$scope.resultAPI.id_user;
$scope.isauthenticated=$scope.resultAPI.isauthenticated;
$scope.user_role=$scope.resultAPI.user_role;
$scope.complete_name=$scope.resultAPI.complete_name;
});
And in HTML you should have smth like this:
<input ng-model="selectedUs" />
<input ng-model="selectedPw" />
Thank you all for the answers. I found my error:
dataService.getData(function(u, p, data) {
And here was my error
dataService.getData(u, p, function(data) {
I was putting u and p beside data, unforgivable error. Thank you all for the help.
I'm trying to find a way to pass a parameter so I can use it in my 'endpoint' variable, as you can see in my code I have the url and in the end of it I have "/clientes", but, in my API I also have "products" and "travels", so I'm looking for a solution to use a variable so I can change the end of the url, otherwise I'll have to create another factories just to get my "products" and my "travels".
angular.module('starter.services', [])
.factory('ServiceClientes', ['$http', function ($http) {
var endpoint = 'http://api.rep.com/api/clientes';
var token = '99KI9Gj68CgCf70deM22Ka64chef2J2J0G9JkD0bDAcbFfd19MfacGf3FFm8CM1hG0eDiIk8';
var credencial = 'rm#w.com:cd8cdx5ef753a06ee79fc75dc7cfe66c';
var origem = 'mobile';
var config = {
url: endpoint,
dataType: 'json',
method: 'GET',
data: '',
headers: {
'X-API-TOKEN': token,
'X-API-CREDENCIAL': credencial,
'X-API-ORIGEM': origem,
"Content-Type": "application/json"
}
};
return {
getAll: function () {
return $http(config);
}
};
}]);
controller:
.controller('PlaylistsCtrl', function ($scope, ServiceClientes) {
ServiceClientes.getAll().success(function (data) {
$scope.playlists = data.dados;
}).error(function (error) {
console.log(error);
});
})
Then make your function injectable with a parameter:
var endpoint = 'http://api.rep.com/api/';
var config = {
dataType: 'json',
method: 'GET',
data: '',
headers: {
'X-API-TOKEN': token,
'X-API-CREDENCIAL': credencial,
'X-API-ORIGEM': origem,
"Content-Type": "application/json"
}
};
return {
getAll: function (url) {
config.url = endpoint + url;
return $http(config);
}
};
controller:
ServiceClientes.getAll("clientes").success(function (data) {
I am using a angular $resource like the one below.
angular.module('app')
.factory('data', function ($resource) {
var Con = $resource('/api/data', {}, {
update : {method : 'PUT'}
});
return {
getData : function (user_id, callback) {
return Con.query({user_id : user_id}, function (data) {
cb(data); // (breakpoint) HERE data is not good
}, function (err) {
cb(err);
}).$promise;
}
};
});
This is what I get when a put a breakpoint on data :
[
['w','e','l','c','o','m','e'],
['h','e','l','l','o']
]
howerver, the server sends :
['welcome','hello']
anyone know why the strings get split?
Thank you
You've run into a fun bug with angular's $resource where it cannot handle a raw array of strings; as a workaround, you can do one of three things:
use the $http service instead
send an object-wrapped response via the server eg: { "stuff" : [ "your", "strings" ] }
force the response data into the above format client-side; $resource eg: methodName: {method:'GET', url: "/some/location/returning/array", transformResponse: function (data) {return {list: angular.fromJson(data)} }} and then access it as data.list
See my answer at https://stackoverflow.com/a/22491240/626810
This works for RAW response. This is a slightly different version from the answer above but this is generic and is not only dependent on JSON response. This will basically mutate RAW response to String format. You will need to access $resource promise result as result.responseData
getAPIService() {
return this.$resource(this.apiUrl, {}, {
save: {
method: 'POST',
headers: {
'Accept': 'text/plain, text/xml',
'Content-Type': 'text/xml'
},
transformResponse: function (data) { return { responseData: data.toString() } }
}
});
}
Use $http instead of $resource
getRiskCount: function (Id,Type) {
var deferred = $q.defer();
var resource = $resource(urlResolverFactory.hostUrl() + '/api/getstudentriskcount',
{}, { query: { method: 'GET', isArray: false } }
);
resource.query({ userId: Id,userType: Type }, function (data) {
deferred.resolve(data);
}, function (error) {
deferred.reject(error);
});
return deferred.promise;
}
Result - ['4','5','6','7']
getRiskCount: function (Id,Type) {
var apiUrl = urlResolverFactory.hostUrl() + '/api/getstudentriskcount';
apiUrl += '?userId=' + Id,
apiUrl += '&userType=' + Type;
var deferred = $q.defer();
var promise = $http({
method: 'GET',
url: apiUrl,
}).success(function (data) {
deferred.resolve(data);
}).error(function (data, status) {
deferred.reject(data);
});
return promise;
}
Result - [4567]
I have a function which does a http POST request. The code is specified below. This works fine.
$http({
url: user.update_path,
method: "POST",
data: {user_id: user.id, draft: true}
});
I have another function for http GET and I want to send data to that request. But I don't have that option in get.
$http({
url: user.details_path,
method: "GET",
data: {user_id: user.id}
});
The syntax for http.get is
get(url, config)
An HTTP GET request can't contain data to be posted to the server. However, you can add a query string to the request.
angular.http provides an option for it called params.
$http({
url: user.details_path,
method: "GET",
params: {user_id: user.id}
});
See: http://docs.angularjs.org/api/ng.$http#get and https://docs.angularjs.org/api/ng/service/$http#usage (shows the params param)
You can pass params directly to $http.get() The following works fine
$http.get(user.details_path, {
params: { user_id: user.id }
});
Starting from AngularJS v1.4.8, you can use
get(url, config) as follows:
var data = {
user_id:user.id
};
var config = {
params: data,
headers : {'Accept' : 'application/json'}
};
$http.get(user.details_path, config).then(function(response) {
// process response here..
}, function(response) {
});
Solution for those who are interested in sending params and headers in GET request
$http.get('https://www.your-website.com/api/users.json', {
params: {page: 1, limit: 100, sort: 'name', direction: 'desc'},
headers: {'Authorization': 'Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=='}
}
)
.then(function(response) {
// Request completed successfully
}, function(x) {
// Request error
});
Complete service example will look like this
var mainApp = angular.module("mainApp", []);
mainApp.service('UserService', function($http, $q){
this.getUsers = function(page = 1, limit = 100, sort = 'id', direction = 'desc') {
var dfrd = $q.defer();
$http.get('https://www.your-website.com/api/users.json',
{
params:{page: page, limit: limit, sort: sort, direction: direction},
headers: {Authorization: 'Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=='}
}
)
.then(function(response) {
if ( response.data.success == true ) {
} else {
}
}, function(x) {
dfrd.reject(true);
});
return dfrd.promise;
}
});
You can even simply add the parameters to the end of the url:
$http.get('path/to/script.php?param=hello').success(function(data) {
alert(data);
});
Paired with script.php:
<? var_dump($_GET); ?>
Resulting in the following javascript alert:
array(1) {
["param"]=>
string(4) "hello"
}
Here's a complete example of an HTTP GET request with parameters using angular.js in ASP.NET MVC:
CONTROLLER:
public class AngularController : Controller
{
public JsonResult GetFullName(string name, string surname)
{
System.Diagnostics.Debugger.Break();
return Json(new { fullName = String.Format("{0} {1}",name,surname) }, JsonRequestBehavior.AllowGet);
}
}
VIEW:
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
<script type="text/javascript">
var myApp = angular.module("app", []);
myApp.controller('controller', function ($scope, $http) {
$scope.GetFullName = function (employee) {
//The url is as follows - ControllerName/ActionName?name=nameValue&surname=surnameValue
$http.get("/Angular/GetFullName?name=" + $scope.name + "&surname=" + $scope.surname).
success(function (data, status, headers, config) {
alert('Your full name is - ' + data.fullName);
}).
error(function (data, status, headers, config) {
alert("An error occurred during the AJAX request");
});
}
});
</script>
<div ng-app="app" ng-controller="controller">
<input type="text" ng-model="name" />
<input type="text" ng-model="surname" />
<input type="button" ng-click="GetFullName()" value="Get Full Name" />
</div>
For sending get request with parameter i use
$http.get('urlPartOne\\'+parameter+'\\urlPartTwo')
By this you can use your own url string