I have created a simple app with Spring and AngularJS with CRUD functions.
Now, my scope variable that contains the arraylist that I pass is not updating when I create a new one.
This is my code for my AngularJS controller
$scope.agency = {id: null, name: '', contact: '', employees: []};
$scope.agencies = [];
$scope.getAllAgencies = function() {
AgencyService.getAllAgencies()
.then(
function (response) {
$scope.agencies = response;
}
)
};
$scope.getAllAgencies();
$scope.createAgency = function(agency) {
AgencyService.createAgency(agency)
.then(
$scope.getAllAgencies(),
function(errReponse){
console.error('Error while creating Agency.');
}
);
};
$scope.submit = function () {
console.log("Saving new Agency");
$scope.createAgency($scope.agency);
$scope.reset();
};
$scope.reset = function(){
$scope.agency = {id: null, name: '', contact: '', employees: null};
$scope.myForm.$setPristine(); //reset Form
};
Service
App.factory('AgencyService', ['$http', '$q', function($http, $q) {
return {
getAllAgencies: function() {
return $http.get('/agency')
.then(
function(response) {
return response.data;
},
function(errResponse){
console.error('Error while fetching agencies');
return $q.reject(errResponse);
}
)
},
createAgency: function(agency) {
console.log("Creating Agency");
return $http.post('/agency', agency)
.then(
function (response) {
return response.data;
},
function (errResponse) {
console.error('Error while create agency');
return $q.reject(errResponse);
}
)
}
};
}]);
And these are my methods in Spring
Get Agencies
#RequestMapping(value = "/agency", method = RequestMethod.GET)
public ResponseEntity<List<Agency>> getAllAgencies() {
List<Agency> agencies = agencyService.getAllAgencies();
if (agencies.isEmpty()) {
return new ResponseEntity<List<Agency>>(HttpStatus.NO_CONTENT);
}
return new ResponseEntity<List<Agency>>(agencies, HttpStatus.OK);
}
Creation of Agency
#RequestMapping(value = "/agency", method = RequestMethod.POST)
public ResponseEntity<Void> createAgency(#RequestBody Agency agency, UriComponentsBuilder ucBuilder) {
if(agencyService.isAgencyExists(agency)) {
System.out.println("CONFLICT");
return new ResponseEntity<Void>(HttpStatus.CONFLICT);
}
agencyService.saveAgency(agency);
HttpHeaders headers = new HttpHeaders();
headers.setLocation(ucBuilder.path("/agency/{id}").buildAndExpand(agency.getId()).toUri());
return new ResponseEntity<Void>(headers, HttpStatus.CREATED);
}
Note: that when I debug, after the post method it does not continue to my get method.
There is no error in this, when I reload it gets all including the one I just created.
Thanks!
I think the create agency function call should be like below:
$scope.createAgency = function(agency) {
AgencyService.createAgency(agency)
.then(
$scope.getAllAgencies,
function(errReponse){
console.error('Error while creating Agency.');
}
);
};
first parameter in then should be the function "$scope.getAllAgencies" instead you are passing the value the function returned "$scope.getAllAgencies()".
Related
I am trying to post a file (single file or multiple files) along with some JSON data using AngularJS and Spring MVC.
I tried as shown below:
JS:
(function () {
'use strict';
var myApp = angular.module('app');
myApp.controller('filesWithJSONController', function ($scope, fileUploadService) {
$scope.uploadFile = function () {
var file = $scope.myFile;
var uploadUrl = myApplnURL + '/showInfo/getInformationTest';", //Url of web service
var fd=new FormData();
angular.forEach($scope.files,function(file){
fd.append('file',file);
});
fd.append('properties', new Blob([JSON.stringify({
"name": "root",
"password": "root"
})], {
type: "application/json"
}));
promise = fileWithJSONService.sendInformation(fd,uploadUrl);
promise.then(function (response) {
$scope.serverResponse = response;
}, function () {
$scope.serverResponse = 'An error has occurred';
})
};
});
})();
(function () {
'use strict';
var myApp = angular.module('app');
myApp.service('fileWithJSONService', function ($http, $q) {
this.sendInformation = function (fd, uploadUrl) {
var deffered = $q.defer();
var config = {
headers : {
'Content-Type': undefined
}
}
$http.post(uploadUrl, fd, config).then(function (response) {
console.log("response " + response);
}, function (errResponse) {
console.error('Error in request' + errResponse);
deferred.reject(errResponse);
});
...
Spring Controller:
#Controller
#RequestMapping("/showInfo")
public class InfoController{
#RequestMapping(value = "/getInformationTest", method = RequestMethod.POST, consumes = {"multipart/form-data"})
#ResponseBody
public String sendInformationTest(#RequestPart("properties") ConnectionProperties properties, #RequestPart("file") List<MultipartFile> multiPartFileList){
System.out.println("In spring controller");
//business logic
}
With the above code, it is showing the multiPartFileList size as zero in Spring Controller.
But if I change the code to take only one file instead of multiple files, it is showing the file information successfully. Any input?
try with:
var fd = new FormData();
fd.append('file', file);//replace with forEach
$http.post(uploadUrl, fd, {
transformRequest: angular.identity,//overrides Angular's default serialization, leaving our data intact.
headers: {'Content-Type': undefined}//lets the browser detect the correct Content-Type as multipart/form-data, and fill in the correct boundary.
})
.success(function(){})
.error(function(){});
Backend - Spring:
#RequestMapping(value ="/upload", method = RequestMethod.POST)
public ResponseEntity handleFileUpload(#RequestParam("file") MultipartFile[] files){
//add the others params & logic
}
I tried this code below...can anyone kindly help me how to pass the params to the spring method and is it a correct implementation in angularjs.
#GetMapping("/extended-registered-time")
public ResponseEntity<List<Registered_time>> getSubLeaves(#ApiParam Pageable pageable) {
log.debug("REST request to get registered time : {}", pageable);
LocalDate startDate = LocalDate.of(2018,01,15);
LocalDate endDate = LocalDate.of(2018,01,24);
List<Registered_time> result = ExtendedRegisteredTimeService.
getSelectedRegisteredTime(startDate,endDate);
return new ResponseEntity<>(result, HttpStatus.OK);
}
This is the frontend implementation(AngularJs)
.factory('RegisteredTimeService', RegisteredTimeService);
RegisteredTimeService.$inject = ['$resource'];
function RegisteredTimeService ($resource) {
var userName="HGajanayake";
var resourceUrl = '/api/extended-registered-time/{'+userName+'}';
return $resource(resourceUrl, {}, {
'query': {
method: 'GET',
isArray: true
},
'status':{
method:"POST",
isArray:true,
I couldnt get over with #requestParams so I choosed #pathVariable instead.I got the correct result.
This is my Service
function RegisteredTimeService ($resource) {
var userName="HGajanayake";
// var resourceUrl = '/api/extended-registered-time?employee='+userName;
var resourceUrl = "/api/extended-registered-time/:employee";
return $resource(resourceUrl, {}, {
'query': {
method: 'GET',
isArray: true
},
This is my api endpoint
#GetMapping("/extended-registered-time/{employee}")
#ResponseBody
public ResponseEntity<List<Registered_time>> getSubLeaves(#PathVariable String employee) {
List<Registered_time> result = ExtendedRegisteredTimeService.getSelectedRegisteredTime(employee);
return new ResponseEntity<>(result, HttpStatus.OK);
}
This is the controller where I call the service
function RegisteredTimeController ($rootScope, $scope, $state, Employee, RegisteredTimeService,Profile,$resource) {
var firstName="HGajanayake";
var c=RegisteredTimeService.query({employee:firstName},function(result) {
var v=result;
console.log(v);
});
I want to upload to server multiple files. Here is my Angular code:
app.directive('fileModel', ['$parse', function ($parse) {
return {
restrict: 'A',
link: function (scope, element, attrs) {
var model = $parse(attrs.fileModel);
var modelSetter = model.assign;
element.bind('change', function () {
scope.$apply(function () {
modelSetter(scope, element[0].files);
});
});
}
};
}]);
And part of the controller:
var fd = new FormData();
fd.append('files', $scope.file);
fd.append('ticketDto', JSON.stringify(data));
$http({
method: 'POST',
url: url,
headers: {
'Content-Type': undefined
},
data: fd,
arrayKey: '',
transformRequest: function (data, headersGetterFunction) {
return data;
}
})
The problem is that in controller:
public void createTicket(#RequestParam(value = "files", required = false) List<MultipartFile> files,
Authentication authentication,
#RequestParam(value = "ticketDto", required = false) String name)
'files' list is always empty (I also tried MultipartFile[] instead of list). It works only if in directive return not all files, but one, for example:
scope.$apply(function () {
modelSetter(scope, element[0].files[0]);
});
instead of
scope.$apply(function () {
modelSetter(scope, element[0].files);
});
Finally I got it. The solution is to add all files to the FormData apart, not as list or array:
angular.forEach($scope.file, function (value, key) {
fd.append('files', value);
})
And then in Spring controller:
public void createTicket(#RequestParam(required = false) MultipartFile[] files)
The array contains all appended files.
I am making SPA using AngularJS in Spring 4 with Hibernate 5.
I'm getting an error while passing JSON array from the AngularJS controller to the Spring Controller.
All fields value successfully coming in angular JSON array, but not passing in Spring controller.
Error: Could not read JSON: ; nested exception is
com.google.gson.JsonSyntaxException:
My project structure is like below.
Spring_Hibernate_MVC
=src
-com->karmesh->mvcApp->controller->register->RegisterController.java
=WebContent
-js->app->RegisterController.js
-Views->Register.html
Register,html
<div id="DivRegisterMain" ng-controller="RegisterController">
<form name="myForm" novalidate>
:::://Form fields here.
<input type="submit" value="SubmitTest" ng-click="submit()" ><br>
</form>
</div>
app.js
var routeApp=angular.module("RouteApp",['ngRoute']);
RegisterController.js
routeApp.controller("RegisterController", function($scope, $http) {
$scope.regJson = {
"is" : 1,
"fname" : "",
"lname" : "",
"gender" : "",
"dob" : "",
"email" : "",
"contact" : "",
"yop" : "",
"degree" : "",
"branch" : "",
"perc" : "",
"state" : "",
"city" : ""
};
$scope.studentList = [];
$scope.submit = function() {
var req = {
method: 'POST',
url: 'http://localhost:8050/Spring_Hibernate_MVC/registerStudent.do',
data: $scope.studentList,
};
$http(req).
then(function(response){
console.log(response); // prints true or false
if (response)
console.log("in success");
else
console.log("in fail");
$scope.studentList=[];
}, function(response){
console.log(response.status);
console.log("in error");
});
};
RegisterController.java
#EnableWebMvc
#RestController
#RequestMapping("/")
public class RegisterController {
#Autowired
private RegisterService registerService;
public RegisterController() {
System.out.println(this.getClass().getSimpleName() + "created..");
}
#ResponseBody
#RequestMapping(value="/registerStudent.do", method = RequestMethod.POST)
public boolean registerStudent(#RequestBody List<RegisterDTO> stdList) {
System.out.println("inside controller..");
if (stdList != null) {
System.out.println("success...");
}
return registerService.isStudentExist(stdList);
}
}
use JSON Serialization/Deserialization
your request should be
var req = {
method: 'POST', url:'http://localhost:8050/Spring_Hibernate_MVC/registerStudent.do',
data: JSON.stringify($scope.studentList),
};
your spring controller
#ResponseBody
#RequestMapping(value="/registerStudent.do", method = RequestMethod.POST)
public boolean registerStudent(#RequestBody string data) {
List<RegisterDTO> stdList = JsonConvert.DeserializeObject<RegisterDTO>(data); // find java jsondeserializer
System.out.println("inside controller..");
if (stdList != null) {
System.out.println("success...");
}
return registerService.isStudentExist(stdList);
}
You are missing contentType: 'application/json' in your request!
RegisterController.js
$scope.submit = function() {
var req = {
method: 'POST',
url: 'http://localhost:8050/Spring_Hibernate_MVC/registerStudent.do',
data: angular.toJson($scope.studentList),// note this
};
};
download gson jar file.
RegisterController.js
#ResponseBody
#RequestMapping(value = "/registerStudent.do", method = RequestMethod.POST)
public boolean registerStudent(#RequestBody String data) {
Gson googleJson = new Gson();
ArrayList stdList = googleJson.fromJson(data, ArrayList.class);
if (stdList != null) {
// store your stdList
}
return registerService.isStudentExist(stdList);
}
I have built an application with Spring-boot and AngularJS with the REST End Point application. I got a little stuck with #RequesMapping in Spring Controller I've made. The problem is, I have the example url:
"localhost:8080/foo/bar/api/cardGenerated/0102".
'01' is first parameter and '02' is second parameter. How can I mapped into #RequestMapping Spring controller to get a url above.
Here's my controller :
#RestController
#RequestMapping("/api")
public class CardGeneratedResource {
#RequestMapping(value = "/cardGenerated/{branchCode}{cardType}",
method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)
#Timed
public ResponseEntity<CardGenerated> get(#PathVariable("branchCode") String branchCode,
#PathVariable("cardType") String cardType,
HttpServletResponse response) {
log.debug("REST request to get CardGenerated : " + branchCode + " and " + cardType);
CardGenerated cardGenerated = cardGeneratedRepository.
findTopByBranchCodeAndCardTypeOrderByCardNumberDesc(branchCode, cardType);
if (cardGenerated == null) {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
return new ResponseEntity<>(cardGenerated, HttpStatus.OK);
}
}
so this is my AngularJS $resource:
'use strict';
angular.module('itmApp')
.factory('CardGenerated', function ($resource) {
return $resource('api/cardGenerated/:branchCode:cardType', {}, {
'query': { method: 'GET', isArray: true},
'get': {
method: 'GET',
transformResponse: function (data) {
data = angular.fromJson(data);
return data;
}
}
});
});
I always got 'Failed to load resource: the server responded with a status of 404 (Not Found)'.
Here you are missing / .
You have two path variable here.so default url is
localhost:8080/foo/bar/api/cardGenerated/FIRST_PATH_VARIABLE/SECOND_PATH_VARIABLE
branchCode (First path variabel)
cardType (Second path variable)
#RequestMapping(value = "/cardGenerated/{branchCode}/{cardType}"
And in frontend side too the same mistake while registering factory definition.
api/cardGenerated/:branchCode/:cardType'
All method is like
#RestController
#RequestMapping("/api")
public class CardGeneratedResource {
#RequestMapping(value = "/cardGenerated/{branchCode}/{cardType}",
method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)
#Timed
public ResponseEntity<CardGenerated> get(#PathVariable("branchCode") String branchCode,
#PathVariable("cardType") String cardType,
HttpServletResponse response) {
log.debug("REST request to get CardGenerated : " + branchCode + " and " + cardType);
CardGenerated cardGenerated = cardGeneratedRepository.
findTopByBranchCodeAndCardTypeOrderByCardNumberDesc(branchCode, cardType);
if (cardGenerated == null) {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
return new ResponseEntity<>(cardGenerated, HttpStatus.OK);
}
}
and angular factory is like
'use strict';
angular.module('itmApp')
.factory('CardGenerated', function ($resource) {
return $resource('api/cardGenerated/:branchCode/:cardType', {}, {
'query': { method: 'GET', isArray: true},
'get': {
method: 'GET',
transformResponse: function (data) {
data = angular.fromJson(data);
return data;
}
}
});
});
NOTE: First try with any rest client or postman and make sure backend api is working properly also angular side check parameters are being passed correctly.