I am calling a Spring API from AngularJS, where I am trying to pass a list of model object as the param.
data.append('updatedItems', $scope.QuoteList);
$http.post('updateQuotes', data).success(function(response) {
console.log(response);
});
Then in Spring controller, I am trying to receive as below,
#RequestMapping(value = "/updateQuotes", method = RequestMethod.POST)
public ArrayList<ConsumerPrice> updateQuotes(#RequestBody List<ConsumerPrice> updatedItems, ConsumerPrice consumerPrice) {
System.out.println(updatedItems);
return null;
}
At this point, I get an exception as mentioned below. I am not sure if this is the correct approach to pass a list from Angular to Spring controller.
Invalid mime type "application/json;charset=utf-8, multipart/form-data;
I found few guidance in the internet and tried like, providing the consumes header but nothing helped. Any guidance will be great
I tried providing #PathVariable at the spring controller but didnt help
Finally I was able to resolve this. There is nothing in the spring controller but i changed the way we pass the Javascript array from Angular controller.
The first 2 lines down below is the difference on how I add the list to formdata array. That helped me to fetch the values in Spring Controller.
$scope.formData = [];
$scope.formData = $scope.cQuoteList;
$http.post('updateQuotes', $scope.formData).success(function(response) {
$scope.userQuotes();
});
Related
I am creating a project in AngularJs at frontend and Spring MVC in backend.
Now assume when a used logged in and if he wants to update his information, for this i have created an api which request for emailid and update the rest object in database of that email id
Now i have some questions,
1.) I dont want to use CookieStore or others sessionStorage or localstorage (because of my personal vulnerability experience and also i want to use session only) in Angular, how can i do it in angular with Spring MVC.
2.) How can i retrieve the email id from session to update data?
3.)If a user goes to another page how can i maintain that session in another page, how can i check that session is there and user is authentic to see the page
Read a lot about it but unable to find the exact solution with session. Answer over there is manage it by cookieStore.or localstorage, Please help
Let's try and see what is happening here using cookies is the right way to this, you may think it is not safe but is the safest way to do it. With cookies you will be sharing the same session in all tabs, so you can handle in all tabs and share it.
There is also an alternative option and is using URL rewriting, quoting #vanje in this question in stackoverflow
the session is only identified via a URL parameter containing the session ID. So every internal URL of your web application has to be enhanced with this parameter using the method HttpServletResponse.encodeURL(). If you are using a web framework like Wicket, chances are good that this is already done for you.
Lets go now with the Angular JS - Spring MVC approach:
There is no need to access the session within the Angular JS front-end, if you need to use it and you are using JSP you may use scriplet to retrieve the information openening a <%= session.getAttribute("user") %> , but as I said there is no need to do this. You may call your function, and retrieve this information in your controller in Spring.
You have a controller in angular JS that calls with http to your REST controller in Spring such like this. assuming that you save your user first in session:
$scope.getUserInfo= function () {
$http.get(appContextPath +'/rest/getuser/').success(function (data) {
$scope.user= data;
});
};
You may have a request mapping for the URL above:
#RequestMapping(value = "/rest/getuser", method = RequestMethod.GET)
#ResponseBody
public User getUserInfo (HttpSession session) {
User nUser = session.getAttribute("user");
return nUser;
}
I think the best way is to create a method in your AngularJS controller and then call it.
Java code:
#RequestMapping(value = "/menu/get", method = RequestMethod.GET, headers="Accept=*/*")
public #ResponseBody Empleado showMenu(HttpSession session) {
Empleado empleado = (Empleado) session.getAttribute("empleado");
return empleado;
}
AngularJS code:
angular.module('myModule')
.controller('myMenuController', ['$scope', '$http'
function($scope, $http){
getEmpleadoInfo = function () {
$http.get(myContextPage + '/menu/get')
.then(function(data) {
$scope.empleado = data;
})
}
getEmpleadoInfo();
}]);
This way, when you load the page, the object will be loaded on the scope.
I'm exploring how jhipster manipulates data. I have found $http.get() in getProfileInfo method in ProfileService Service whitch interacting restful api :
function getProfileInfo() {
if (!angular.isDefined(dataPromise)) {
dataPromise = $http.get('api/profile-info').then(function(result) {
if (result.data.activeProfiles) {
var response = {};
response.activeProfiles = result.data.activeProfiles;
response.ribbonEnv = result.data.ribbonEnv;
response.inProduction = result.data.activeProfiles.indexOf("prod") !== -1;
response.swaggerDisabled = result.data.activeProfiles.indexOf("no-swagger") !== -1;
return response;
}
});
}
return dataPromise;
}
and some where i have found $resouce() manipulating GET method. for example in BankAccount factory :
var resourceUrl = 'api/bank-accounts/:id';
I searched for when to use $http and when to use $resource and i found this :
AngularJS $http and $resource
why hipster is not following consistent way of interacting API and manipulating data!!?
so jhipster, when to use $http and when to use $resource in services??
We use $resource when requesting a RESTful endpoint, for example for an entity. $resource provides basic REST operations easily whereas $http is more specific.
For profile we only need to GET /profile-infos so it's useless to use $resource because we'll never need to call POST or DELETE on that URL.
$http will fetch you the entire page or complete set of data from a given URL whereas $resouce uses http but will help you to fetch a specific object or set of data.
$resource is fast and we use it when we need to increase the speed of our transaction.
$http is used when we are concerned with the time.
I was wondering if we can load multiple json files using a factory and a controller.
Im pulling classifieds.json and myWords.json.
Im seeing content from the former, but the content from the latter is not being displayed
This is how i tired to incorporate it. I've checked the propriety of myWords.json against a json formatter, so i know for sure that its all right.
I guess, im doin sthg wrong here. Id appreciate if you could guide me in the right direction.
Factory
Controller
In order to fetch data from multiple sources, the currect way is to use one method for each data source.
Factory:
function getClassified() {
return $http.get('data/classified.json');
}
function getMyWords() {
return $http.get('data/myWords.json');
}
return {
getClassified : getClassified,
getMyWords : getMyWords
}
Controller
classifiedsFactory.getClassified().then(function(data) {
$scope.classified = data;
};
classifiedsFactory.getMyWords().then(function(data) {
$scope.myWords = data;
}
If you have more than 2 source that you want to get together, you can use $q service in your factory:
function getAllData() {
var source1 = $http.get('source1.json');
var source2 = $http.get('source2.json');
...
...
return $q.all([source1, source2, ...]);
}
This will resolve only when all data have been recieved and you can get it in your controller.
Don't forget to include $q in your factory function dependencies
Demo link
Hi Ashim09,
Here I added sample for multiple json call in factory..
I'm having a slight issue with my ability to consume REST data retrieved via Restangular in an angular controller. I have the following code which works fine for a list of accounts:
var baseAccounts = Restangular.all('accounts');
baseAccounts.getList().then(function(accounts) {
$scope.accounts = accounts;
});
This works perfectly for a list. I use similar syntax for a single account:
var baseAccount = Restangular.one('accounts');
baseAccount.getList(GUID).then(function(returnedAccount) {
$scope.currentAccount = returnedAccount;
});
I am using ng-repeat as the handling directive for my first request. I am attempting to bind with {{ account.name }} tags for the single request, but it does not seem to display any data despite the request being made properly. GUID is the parameter I must pass in to retrieve the relevant record.
I have combed through Restangular docs and it seems to me like I am composing my request properly. Any insight would be greatly appreciated.
EDIT: I've tried all of the solutions listed here to no avail. It would seem Restangular is submitting the correctly structured request, but when it returns it through my controller it shows up as just a request for a list of accounts. When the response is logged, it shows the same response as would be expected for a list of accounts. I do not believe this is a scoping issue as I have encapsulated my request in a way that should work to mitigate that. So, there seems to be a disconnect between Request -> Restangular object/promise that populates the request -> data-binding to the request. Restangular alternates between returning the array of accounts or undefined.
Have you looked at:
https://github.com/mgonto/restangular#using-values-directly-in-templates
Since Angular 1.2, Promise unwrapping in templates has been disabled by default and will be deprecated soon.
Try:
$scope.accounts = baseAccounts.getList().$object;
try:
var baseAccount = Restangular.one('accounts', GUID);
baseAccount.get().then(function(returnedAccount) {
$scope.currentAccount = returnedAccount;
});
The problem here is that it's expecting an array to be returned. I'm assuming that you are expecting an account object. Thus we need to use the get function, intead of getList()
The one() function has a second argument that accepts an id e.g. .one('users', 1). You can take a use of it.
CODE
var baseAccount = Restangular.one('accounts', 1); //1 would be account id
baseAccount.getList('account').then(function(returnedAccount) {
$scope.currentAccount = returnedAccount;
});
OR
var baseAccount = Restangular.one('accounts', 1); //1 would be account id
baseAccount.all('account').getList().then(function(returnedAccount) {
$scope.currentAccount = returnedAccount;
});
For more info take look at github issue
Hope this could help you, Thanks.
I've read up many articles on angularjs and REST but could not found any solution. Through java script I am calling api method, which is routed method as:
[Route("api/Comments/{docId}/comment/{revId}/get/{size}/getNumber/{number}")]
[HttpPost]
public IEnumerable<Student> Get(int docId,int revId,int size, int number)
{
// loadienter code hereng list here
return list.ToList();
}
//java script code
var url='api/students/' + docId + '/student/' + revId + '/get/'+size+'/getNumber/'+number';
$http.get(url).success(function (response) {
if (callback) callback(response.result);
};
But the method in controller class is not executing..How to solve this issue? P
Please give me some suggestions..
If in your angular controller you have just that code for the call to the api it looks like when you are constructing your url variable you haven't included on the front of it what the domain is that you are hitting. such as http://localhost/ if your debugging it locally.
Also your route is defined to start as api/comments/ on your WebApi however in your javascript url you have api/students/