Angular JS - response from GET not available in $scope - angularjs

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.

Related

$resource PUT operation not extracting id

I can't seem to get an "id" to come through to the $resource function from the controller. Here is the offending code...
Controller:
$scope.update_user_extra = function () {
UserExtraResource.update($scope.user_extra_details, function (data) {
$scope.user_extra_details = data;
$scope.user_extra_details = {mobile:data.mobile,
landline:data.landline,
position:data.position,
notes:data.notes,
language:data.language};
});
};
Resource:
module.exports = function ($resource) {
return $resource('/api/user_extra/:id/', { id: '#_id' }, {
details: {method: 'GET', url: '/api/user_extra/details'},
update: {method: 'PUT'}
});
};
The GET works fine but the custom PUT returns:
http://127.0.0.1:8000/api/user_extra/ 404 (Not Found)
hardcoding the id like:
return $resource('/api/user_extra/1/', { id: '#_id' }, {
works fine. Any help is much appreciated!!
hmm ... changing this line to:
return $resource('/api/user_extra/:id/', { id: ̶'̶#̶_̶i̶d̶'̶ '#id' }, {
seems to have done it. Thank you very much!
If the default parameter value is prefixed with #, then the value for that parameter will be extracted from the corresponding property on the data object. For example, if the defaultParam object is {someParam: '#someProp'} then the value of someParam will be data.someProp.
In the above question, the PUT operation was trying to extract the property _id of the data object when the name of the property was actually id.
For more information, see AngularJS $resource API Reference.

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

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 {} */
}

How to tell what are the mandatory parameters when calling an AngularJS $resource

I know that is it possible to create custom methods using the AngularJs $resource, but I would like to know if it is possible to tell the person that is using the resource what parameter they should provide when calling it.
I am not talking about default values, but more like a guideline of what to provide to call the $resource.
$resource("/api/myEntity/:id", { id: '#id' }, {
getBySlug: {
method: "GET",
url: "/api/MyEntity/GetBySlug/"
//something like : paramsToProvide : {slug : "", etc.}
},
});
//...
myEntity.myCustomMethod({}, function(){
//callback...
});
Create a factory which exposes an API, and throw an error or log a warning if a function is called without required parameters.
var myEntity = $resource(...);
return {
getBySlug: function getBySlug(slug) {
if (slug === undefined) {
throw new Error('Please provide a slug');
}
return myEntity.getBySlug({slug: slug}).$promise;
}
};

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.

Angular.js delete resource with parameter

My rest api accpets DELETE requests to the following url
/api/users/{slug}
So by sending delete to a specified user (slug) the user would be deleted. here is the service code:
angular.module('UserService',['ngResource']).factory('User', function($resource){
var User = $resource('/api/users/:id1/:action/:id2', //add param to the url
{},
{
delete_user: {
method: 'DELETE',
params: {
id1:"#id"
}
},
update: {
method: 'PUT',
params: {
id1:"#id"
}
}
});
return User;
});
I call the delete function via
user.$delete_user({id:user.id}, function(){}, function(response){});
However the request seems to be send to the wrong url.
/api/users?id=4
So the parameter is actually missing, as a result I get a 405 Method not allowed. Is there any chance to send the delete request in the style of my api?
params is an object of default request parameteres in your actions. If you want url parameters you have to specify them in the second parameter like this:
angular.module('UserService',['ngResource']).factory('User', function($resource){
var User = $resource('/api/users/:id1/:action/:id2', //add param to the url
{id1:'#id'},
{
delete_user: {
method: 'DELETE'
}
});
return User;
});
this works with either:
// user has id
user.$delete_user(function(){
//success
},function(){
// error
});
or
var data = {id:'id_from_data'};
User.delete_user({},data);
or
var params = {id1:'id1_from_params'};
User.delete_user(params);
I've made a plnkr-example - you have to open your console to verify that the DELETE requests are correct.
See parameterDefaults in the Angular resource documentation.
I had this problem for a while I was using a service to add / delete / update categories. While passing in params for get it worked fine but then when deleting it was giving me a ?id=1234 instead of api/resource/1234
I got around this by making the default param a string.
///Controller
Service.delete({categoryId:id}, function(resp){
console.log(resp)//whatever logic you want in here
});
//SERVICES
$resource('api/resource/:categoryId', {"categoryId":"#categoryId"}, {
query:{method:"GET"},
delete:{method:"DELETE"},
});
Should work and the resulting url will be, originally I had categoryId in the default params as a variable name.
api/resource/1234 etc
Just omit the '#' in the parameter
.factory('reportFactory', ['$resource', 'baseUrl', function ($resource, baseUrl) {
return $resource(baseUrl + '/keys/:id', {}, {
delete: { method: 'DELETE',
headers: {
'Content-Type': 'application/json'
},
params: {id: 'id'} }
})
}]);
this will give you:
http://localhost:8080/reports/api/keys/b8a8a8e39a8f55da94fdbe6c
without the question mark
If you want to delete a model, there's no need to add params (params does not work for DELETE anyway):
$resource('/users/:id').delete({id: user.id}, function(res) {
...
})
or
$resource('/users/:role/:id').delete({role: 'visitor', id: user.id});
I'm not sure if it's a bug of ngResource.

Resources