Angular JS - Dynamic URL for $http get - javascript

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.

Related

When uploading image file to server using REST, uploaded file mismatches original client file [duplicate]

unable to send file with angular post call
I am trying to post .mp4 file with some data through ionic 1 with angular 1. While posting through POSTMAN it is fine and working. I am getting Success = false in my application.
in POSTMAN, no headers and data is bellow,
Service url with POST request http://services.example.com/upload.php
body in form data
j_id = 4124, type = text
q_id = 6, type = text
u_id = 159931, type = text
file = demo.mp4, type = file
in my app:
$rootScope.uploadQuestion = function () {
var form = new FormData();
form.append("j_id", "4124");
form.append("q_id", "6");
form.append("u_id", "159931");
form.append("file", $rootScope.videoAns.name); //this returns media object which contain all details of recorded video
return $http({
method: 'POST',
headers: { 'Content-Type': 'multipart/form-data' }, // also tried with application/x-www-form-urlencoded
url: 'http://services.example.com/upload.php',
// url: 'http://services.example.com/upload.php?j_id=4124&q_id=8&u_id=159931&file='+$rootScope.videoAns.fullPath,
// data: "j_id=" + encodeURIComponent(4124) + "&q_id=" + encodeURIComponent(8) + "&u_id=" + encodeURIComponent(159931) +"&file=" + encodeURIComponent($rootScope.videoAns),
data: form,
cache: false,
timeout: 300000
}).success(function (data, status, headers, config) {
if (status == '200') {
if (data.success == "true") {
alert('uploading...');
}
}
}).error(function (data, status, headers, config) {
});
}
RECOMMENDED: POST Binary Files Directly
Posting binary files with multi-part/form-data is inefficient as the base64 encoding adds an extra 33% overhead. If the server API accepts POSTs with binary data, post the file directly:
function upload(url, file) {
if (file.constructor.name != "File") {
throw new Error("Not a file");
}
var config = {
headers: {'Content-Type': undefined},
transformRequest: []
};
return $http.post(url, file, config)
.then(function (response) {
console.log("success!");
return response;
}).catch(function (errorResponse) {
console.error("error!");
throw errorResponse;
});
}
Normally the $http service encodes JavaScript objects as JSON strings. Use transformRequest: [] to override the default transformation.
DEMO of Direct POST
angular.module("app",[])
.directive("selectNgFiles", function() {
return {
require: "ngModel",
link: postLink
};
function postLink(scope, elem, attrs, ngModel) {
elem.on("change", function(event) {
ngModel.$setViewValue(elem[0].files);
});
}
})
.controller("ctrl", function($scope, $http) {
var url = "//httpbin.org/post";
var config = {
headers: { 'Content-type': undefined }
};
$scope.upload = function(files) {
var promise = $http.post(url,files[0],config);
promise.then(function(response){
$scope.result="Success "+response.status;
}).catch(function(errorResponse) {
$scope.result="Error "+errorRespone.status;
});
};
})
<script src="//unpkg.com/angular/angular.js"></script>
<body ng-app="app" ng-controller="ctrl">
<input type="file" select-ng-files ng-model="files">
<br>
<button ng-disabled="!files" ng-click="upload(files)">
Upload file
</button>
<pre>
Name={{files[0].name}}
Type={{files[0].type}}
RESULT={{result}}
</pre>
</body>
Posting with 'Content-Type': 'multipart/form-data'
When posting data using the FormData API, it is important to set the content type to undefined:
function uploadQuestion(file) {
var form = new FormData();
form.append("j_id", "4124");
form.append("q_id", "6");
form.append("u_id", "159931");
form.append("file", file); //this returns media object which contain all details of recorded video
return $http({
method: 'POST',
headers: { 'Content-Type': undefined ̶'̶m̶u̶l̶t̶i̶p̶a̶r̶t̶/̶f̶o̶r̶m̶-̶d̶a̶t̶a̶'̶ }, // also tried with application/x-www-form-urlencoded
url: 'http://services.example.com/upload.php',
data: form,
̶c̶a̶c̶h̶e̶:̶ ̶f̶a̶l̶s̶e̶,̶
timeout: 300000
̶}̶)̶.̶s̶u̶c̶c̶e̶s̶s̶(̶f̶u̶n̶c̶t̶i̶o̶n̶ ̶(̶d̶a̶t̶a̶,̶ ̶s̶t̶a̶t̶u̶s̶,̶ ̶h̶e̶a̶d̶e̶r̶s̶,̶ ̶c̶o̶n̶f̶i̶g̶)̶ ̶{̶
}).then(function(response) {
var data = response.data;
var status = response.status;
if (status == '200') {
console.log("Success");
}
̶}̶)̶.̶e̶r̶r̶o̶r̶(̶f̶u̶n̶c̶t̶i̶o̶n̶ ̶(̶d̶a̶t̶a̶,̶ ̶s̶t̶a̶t̶u̶s̶,̶ ̶h̶e̶a̶d̶e̶r̶s̶,̶ ̶c̶o̶n̶f̶i̶g̶)̶ ̶{̶
}).catch(function(response) {
console.log("ERROR");
//IMPORTANT
throw response;
});
}
When the XHR API send method sends a FormData Object, it automatically sets the content type header with the appropriate boundary. When the $http service overrides the content type, the server will get a content type header without the proper boundary.

How to pass form parameters to Rest using angularjs services?

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.

Use parameters in angular factory for custom header

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) {

$resource.query return split strings (array of char) instead of a string

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]

AngularJS passing data to $http.get request

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

Categories