How can i pass query params as arguments in angularjs http services - angularjs

How can i pass query params as arguments in angularjs http services.
My controller code is:
FetchHeadCategoryService.get({
'officeJndi': officeJndi
}, function (response) {
$scope.headCategories = response;
});
Service.js
module.factory('FetchHeadCategoryService', [
'$resource',
'SYSTEM',
function($resource, SYSTEM) {
return $resource(SYSTEM.ENV.API_END_POINT
+ 'v1/utility/headCategories/:officeJndi ', {
officeJndi : '#officeJndi'
}, {
get : {
method : 'GET',
isArray : true
}
});
} ]);
HeadCategory.java
public Response fetchDocMgmtHeadCategory(#PathParam(value = "officeJndi") final String officeJndi, #QueryParam(value = "limitFrom") final int limitFrom,#QueryParam(value = "noOfRows") final int noOfRows){
..
..
..
}
I can obtain the result without passing the query params by managing them in the code.
But I want to send the value of query params "limitFrom" and "NoOfRows" to the service ,so that i acn fetch the data accordingly.Can somebody HELP.

Try to use params option to send additional data
get : {
method : 'GET',
isArray : true,
params: /* your data {} */
}

Related

Angular $resource and webApi

I am using webApi and have generated the model using entityframework the overload method of the GET(int id) I am trying to call that using the query of the $resource
I am trying to pass an optional parameter to a call using the $resource but get the error [$resource:badcfg] I have had a google and people say add
{
'get': {method: 'GET'},
'query': {method: 'GET', isArray: true}
}
into the function, so I have tried this: but still have no luck.
function minorResource($resource, appSettings) {
return $resource(appSettings.serverPath + "/api/minorworks/:id",
{
'get': {method: 'GET'},
'query': {method: 'GET', isArray: true}
});
}
Would you use 2 separate methods or can the above function be made to work?
For completness here is my Controller call
minorResource.query({id: vm.seachCriteria}, function (data) {
//console.log(data);
vm.minorWork = data;
});
Note that query is used to retrieve an array of objects and get is used to retrieve a single object. That means that with a get you usually sent the id of the object to the API.
So in your case:
var minorWorksResource = $resource(appSettings.serverPath + "/api/minorworks/:id");
// Note that query returns an array.
var works = minorWorksResource.query(function() {
var firstWork = works[0];
});
// Note that we pass an ID that will be fetched in the query string.
var singleWork = minorWorksResource.get({id: 123}, function() {
});
And the WebAPI part:
[RoutePrefix("api/minorworks")]
public class MinorWorksController : ApiController {
public IHttpActionResult Get(int id) {
var singleWork = null;
// Retrieve a single item;
return Ok(singleWork);
}
public IHttpActionResult Get() {
var workList = null;
// Retrieve the whole list.
return Ok(workList );
}
}

Turn request success into error based on response data

I am relatively new to Angular js and trying to use promises along with services and got reference http://plnkr.co/edit/b4HPbX2olM745EfHVcc6?p=preview. But in my application I am getting response as {"Response":"exception while loading Reports List","error":"Exception getting all records.","status":"failure"}. When I get response like this, I need to show an alert message with the message in "error" (i.e., Exception getting all records) and set $scope.data to [] in my controller.What are the changes I need to make to services and controller to handle this. Any help is much appreciated.
In services :
return $q.when(originalRequest)
.then(function(res) {
data = res.ResultSet.Response;
return data;
});
In Controller,
DashboardsDataService.getNetSpendOverTimeData()
.then(function(data) {
$scope.data = data;
});
The following is my original request to Java action class:
var originalRequest = $.ajax({
async : false,
url : "/dash2/dashd2ajax.do",
type : "POST",
data : {
action : 'getNetSpendOverTime',
customerId : selectedAccTd,
carriersId : selectedCarriers,
fromDate : fromDate,
toDate : toDate,
modes : selectedModes,
services : selectedServices,
dateType : selectedDateType,
lanesList : selectedLaneList
},
dataType : "json"
});
return $q.when(originalRequest)
.then(function(res) {
data = res.ResultSet.Response;
return data;
});
If what you're asking is "how do I turn request success into a failure based on result data", then take a look at the following example:
return $q.when(originalRequest).then(function (res) {
if (res.ResultSet.error) {
return $q.reject(res.ResultSet.error);
} else {
return res.ResultSet.Response;
}
});
Using $q.reject() turned your data into a real "promise failure", so in your controller, you can use the normal promise API:
doSomethingAsynchronous().then(function (data) {
$scope.data = data;
}, function (error) {
$scope.data = [];
alert(error);
});

Angular JS - response from GET not available in $scope

I am facing a problem with variables not available in the $scope after a GET request
Route provider has
when('/vote/:surveyId', { templateUrl: 'partials/polllist.html', controller: PollListCtrl }).
and I have a service.js will following code
factory('Vote', function($resource) {
return $resource('vote/:surveyId', {}, {
// Use this method for getting a list of polls
vote : {
method : 'POST',
params : {
surveyId : 'vote'
},
isArray : true
},
getVote : {
method : 'GET',
isArray : true
}
})
})
I have the following code in PollListCtrl
V
ote.vote(voteObj, function(p, resp) {
console.log("outside --- NNNNOOOOO ERRRORRRRR"+$location);
if(!p.error) {
// If there is no error, redirect to the main view
console.log("NNNNOOOOO ERRRORRRRR"+resp);
$scope.vote_data = resp;
$scope.voted = Vote.getVote({
surveyId : surveyId
});
//$location.path('surveys');
//$location.path();
} else {
alert('Could not create survey');
}
});
Can you pls help me with the issue..
I believe that if you want to specify parameters in a GET resource that way, you have to use an # to perform the mapping. Also, you told the resource parameter to use the "vote" variable, but when you tried to call the endpoint, you gave it "surveyId" instead. I kept your definition structure and changed your controller code to match just to keep the changes clear.
Also, you didn't post all of your controller code, so I'm not sure exactly where surveyId (the one you're trying to pass into the route) is coming from; I assume you have it declared somewhere. But if that's supposed to be a scoped variable, you'll want to prepend it with $scope.
factory('Vote', function($resource) {
return $resource('vote/:surveyId', {}, {
vote : {
method : 'POST',
params : {
surveyId : '#vote'//<= Changed
},
isArray : true
},
getVote : {
method : 'GET',
isArray : true
}
})
})
Vote.vote(voteObj, function(p, resp) {
if(!p.error) {
$scope.vote_data = resp;
$scope.voted = Vote.getVote({vote : surveyId}); //<=Changed
} else {
alert('Could not create survey');
}
});
Try that and let me know if you still have trouble.

Passing 'filter' parameter to angular resource (DreamFactory rest api)

I am having an issue with query parameters from my AngularJS app
I am reading documents from MongoDB using DreamFactory rest api like this:
.service('Servant', ['$resource', function($resource) {
// define and return $resource
return $resource('https://mydsp.cloud.dreamfactory.com:443/rest/mongodb/tablename',
{
// set params to bind too
app_name: 'myapp',
fields: '#fields',
limit: '#limit',
offset: '#offset',
filter: '#filter'
},
{
// set update method to 'PUT'
update: {
method: 'PUT'
}
}
)
}]);
This all works great when I set filter like "parameter=value" but I failed to find a way of passing more complicated filter param in JSON format as described here, using $in parameter etc. Does anyone know the right syntax for this?
EDIT:
just tried something like
filter = angular.toJson("{'parameter':{$in:['value1','value2']}}")
with no success...
First...drop the port from your service url. 'https' for dreamfactory specifies port 443. No need for you to do it explicitly. Second...You should be able to pass a SQL style filter as a string in your params. When you set up your $resource the way you have you should be able to pass a params object to it. No need to stringify or toJson anything. DreamFactory should handle it. For example...
Here is your service:
.service('Servant', ['$resource', function($resource) {
return $resource('https://mydsp.cloud.dreamfactory.com/rest/mongodb/tablename',
{
app_name: 'myapp',
fields: '#fields',
limit: '#limit',
offset: '#offset',
filter: '#filter'
},
{
update: {
method: 'PUT'
}
}
}]);
Calling that service with a params object:
// the 'parameter' value in our filter string should relate to a field and/or property
scope.paramsObj = {
fields: '*',
limit: 10,
offset: 0,
filter: 'parameter in (5,15)'
}
// call service and handle promise returned by $resource
Servant.get(scope.paramsObj).then(
function(result) {
// handle success
// like assign to a var or something
// here we just log it
console.log(result)
},
function(error) {
// handle error
// probably should throw an error here
// but we just log it here
console.log(error);
});
EDIT
Ok. So...it should work with SQL style filter strings. An issue has been logged with DreamFactory. In the mean time you can create a custom $resource action to handle the filters and tunnel your GET request through a POST. Easier then it sounds. See code below.
Here is the service with custom action
.service('Servant', ['DSP_URL', '$resource', function (DSP_URL, $resource) {
return $resource(DSP_URL + '/rest/mongohq/Colors', {
// params to bind to
app_name: YOUR_APP_NAME_HERE,
fields: '#fields',
limit: '#limit',
offset: '#offset'
}, {
// custom $resource action
'getFiltered': {
// set our method to post because we have to post
// our filter object
method: 'POST',
// We can transform the data before the post.
// In the circumstance we do need to stringify
// So that's what we do here.
transformRequest: function (data) {
return JSON.stringify(data);
}
}
})
}]);
Here is the controller:
.controller('MongoCtrl', ['$scope', 'Servant', function ($scope, Servant) {
// Create a params object
// This requests all fields.
// And we explicitly set the method to
// GET. We are tunneling a GET request
// through our POST because our filter
// needs to be posted but we really want a GET.
$scope.params = {
fields: '*',
method: 'GET'
};
// Call our Service with our custom $resource action
Servant.getFiltered(
// Send our params
$scope.params,
// Send our filter as post data
{
"filter": {
"color": {
"$in": ["blue", "white"]
}
}
},
// handle success
function (data) {
console.log(data)
},
// handle error
function (error) {
console.log(error)
})
}])
I guess you should stringify your filter data:
resource.update( {
filter: JSON.stringify( {qty:{$in:[5,15]}} )
});
Or in this way:
resource.get({id:123}, function() {
resource.filter = JSON.stringify( {qty:{$in:[5,15]}} );
resource.$update();
});

How do I get data from a Java REST service with angular.js

I'm using the default JEE7 REST application on Netbeans. The REST method that I'm trying to call is:
#GET
#Path("{id}")
#Produces({"application/xml", "application/json"})
public Customer find(#PathParam("id") Integer id) {
return super.find(id);
}
I can successfully get a list of all customers. However, when I get the customer ID on the client side with angular, it generates this URL:
http://localhost:8080/mavenproject2/customers?0=1
(when I passed the ID of 1)
The addition of "?" and the index added "0=" makes the call fail.
http://localhost:8080/mavenproject2/customers/1 works
My service looks like this:
customerServices.factory('customerById', function ($resource) {
return $resource('http://localhost:8080/mavenproject2/customers/:id', {id: "#id"}, {
query: {method: 'GET', isArray: true}
});
})
and my controller looks like this:
.controller('customerDetailsController', function ($scope, $routeParams, customerById) {
$scope.customer = customerById.query($routeParams.customerId);
});
Assistance will be greatly appreciated.
You should pass the argument as object, having the field(s) specified with the #. For your case:
$scope.customer = customerById.query({ id: $routeParams.customerId });
You could try something like this in your controller:
$scope.fetchData = function() {
$http({
method : 'GET',
url : 'http://localhost:8080/mavenproject2/customers/',
params : {id : theIdFromYourCode}
}).success(function(data) {
// do something
}).error(function(data, status) {
// do something if error
});
};
Note that you will have to include the $http module.

Resources