admin管理员组文章数量:1291113
I have one simple web application in JAVA and angularjs. Where users can add persons to app and remove them from mongo database.
My problem is, I don't know exactly how angular municates with java and calls Java functions. For example if i want to delete a person from my database after a button click.
here's some code
persons.html
<a for-authenticated ng-click="remove(s.id)" href=""> <i
class="pull-right glyphicon glyphicon-remove"></i>
</a>
app.js
var app = angular.module('conferenceApplication', [
'ngCookies',
'ngResource',
'ngSanitize',
'ngRoute',
'ui.bootstrap',
'angularFileUpload',
'ngQuickDate']);
app.config(function ($routeProvider) {
$routeProvider
.when('/home', {
templateUrl: '/partials/home.html',
controller: 'HomeCtrl'
})
.when('/speakers', {
templateUrl: '/partials/person-list.html',
controller: 'PersonListCtrl'
})
});
app.controller('PersonListCtrl', function ($scope,$http, $modal, $log, $route, PersonService) {
$scope.remove = function(id) {
var deletedPerson = id ? PersonService.remove(id, function(resp){
deletedPerson = resp;
}) : {};
};
}
PersonService.js
app.service('PersonService', function ($log, $upload, PersonResource) {
this.getById = function (id, callback) {
return PersonResource.get({personId: id}, callback);
};
this.remove = function(id, callback) {
return PersonResource.deleteObject({PersonId: id}, callback);
}
}
PersonResource.js
app.factory('PersonResource', function ($resource) {
return $resource('rest/person/:personId',
{
personId: '@personId'
},
{
'update': { method: 'PUT' }
})
});
also i have a java class where i want to delete this person from database
PersonResource.java
@Controller
@RequestMapping("/person")
public class PersonResource {
@Autowired
private PersonService personService;
@RequestMapping(method = RequestMethod.GET, value = "/{id}")
public ResponseEntity<Person> deleteObject(@RequestBody Person id) {
Person person = personService.findById(id);
personService.deleteObject(id);
return new ResponseEntity<Person>(person, HttpStatus.ACCEPTED);
}
}
PersonRepository
@Override
public void deleteObject(String id) {
getTemplate().remove(new Query(Criteria.where("id").is(id)), Person.class);
}
the getTemplate() returns MongoTemplate.
Can anyone tell me what i am doing wrong to get my entry deleted from database ?
I have one simple web application in JAVA and angularjs. Where users can add persons to app and remove them from mongo database.
My problem is, I don't know exactly how angular municates with java and calls Java functions. For example if i want to delete a person from my database after a button click.
here's some code
persons.html
<a for-authenticated ng-click="remove(s.id)" href=""> <i
class="pull-right glyphicon glyphicon-remove"></i>
</a>
app.js
var app = angular.module('conferenceApplication', [
'ngCookies',
'ngResource',
'ngSanitize',
'ngRoute',
'ui.bootstrap',
'angularFileUpload',
'ngQuickDate']);
app.config(function ($routeProvider) {
$routeProvider
.when('/home', {
templateUrl: '/partials/home.html',
controller: 'HomeCtrl'
})
.when('/speakers', {
templateUrl: '/partials/person-list.html',
controller: 'PersonListCtrl'
})
});
app.controller('PersonListCtrl', function ($scope,$http, $modal, $log, $route, PersonService) {
$scope.remove = function(id) {
var deletedPerson = id ? PersonService.remove(id, function(resp){
deletedPerson = resp;
}) : {};
};
}
PersonService.js
app.service('PersonService', function ($log, $upload, PersonResource) {
this.getById = function (id, callback) {
return PersonResource.get({personId: id}, callback);
};
this.remove = function(id, callback) {
return PersonResource.deleteObject({PersonId: id}, callback);
}
}
PersonResource.js
app.factory('PersonResource', function ($resource) {
return $resource('rest/person/:personId',
{
personId: '@personId'
},
{
'update': { method: 'PUT' }
})
});
also i have a java class where i want to delete this person from database
PersonResource.java
@Controller
@RequestMapping("/person")
public class PersonResource {
@Autowired
private PersonService personService;
@RequestMapping(method = RequestMethod.GET, value = "/{id}")
public ResponseEntity<Person> deleteObject(@RequestBody Person id) {
Person person = personService.findById(id);
personService.deleteObject(id);
return new ResponseEntity<Person>(person, HttpStatus.ACCEPTED);
}
}
PersonRepository
@Override
public void deleteObject(String id) {
getTemplate().remove(new Query(Criteria.where("id").is(id)), Person.class);
}
the getTemplate() returns MongoTemplate.
Can anyone tell me what i am doing wrong to get my entry deleted from database ?
Share Improve this question edited Apr 24, 2014 at 16:05 user3144600 asked Apr 24, 2014 at 15:41 user3144600user3144600 711 gold badge2 silver badges5 bronze badges 6- 1 Well RESTful webservices are used to talk to the Java backend. You should study that (JAX-RS is the name of the Java API) and get familiar with it. But you forgot to actually mention what your problem is. You get an error? If so, what is it? – Gimby Commented Apr 24, 2014 at 15:44
- with that code i have an error Error: SpeakerResource.deleteObject is not a function. – user3144600 Commented Apr 24, 2014 at 15:54
- So a Javascript error. You didn't post the SpeakerResource javascript code though. At this point I have to assume the browser is not lying and the function simply does not exist. – Gimby Commented Apr 24, 2014 at 15:56
- sry edited that. i feel dumb now, but how i could possibly implement that function to tell java to delete that person? – user3144600 Commented Apr 24, 2014 at 16:08
- I would suggest to look at the docs for Angular $resource here: docs.angularjs/api/ngResource/service/$resource. There is also the doc on how to create a custom method, in case you need to implement one. – klode Commented Apr 24, 2014 at 17:25
3 Answers
Reset to default 2So when using GET method usual we fetch some data, if we want to send some data to server (ex. an id for person to be deleted) we use POST method or DELETE method, in my example I'll use POST method for simplification. Angular and java municate thru RESTFUL services (JAX-RS), You cant call java function in angular js or vice verse. I'll show simple example of fetching data and sending data (fetch all persons, delete person with given id).
Here is an example where You can start learning from:
Java Person Controller
@Controller
@RequestMapping(value = "/person")
public class PersonController{
private final PersonService personService;
@Autowired
public PersonController(final PersonService personService) {
this.personService= personService;
}
@RequestMapping(value = "/", method = { RequestMethod.GET })
@ResponseBody
public List<Person> getPersons() {
return personService.getPersons();
}
@RequestMapping(value = "/delete/{personId}", method = { RequestMethod.POST})
@ResponseBody
public HttpStatus deletePerson(@PathVariable final long personId) {
return personService.deletePerson(personId);
}
}
Java Person Service
public class PersonService{
private final PersonRepository personRepository;
@Autowired
public PersonService(final PersonRepository personRepository) {
this.personRepository= personRepository;
}
public List<Person> getPersons() {
return personRepository.findAll();;
}
public HttpStatus deletePerson(final long id) {
if (id > 0) {
personRepository.delete(id);
return HttpStatus.OK;
} else {
return HttpStatus.INTERNAL_SERVER_ERROR;
}
}
}
Java Person Repository
public interface PersonRepository{
public void delete(int personId);
public List<Person> findAll();
}
Angular app.js
(function() {
var app = angular.module('personApp',[]);
app.controller('personCtrl',function($scope,$http){
$scope.getPersons = function(){
$http.get('person/').success(function(response){
$scope.allPersons = response.data;
}).error(function(){
//handle error
})
};
$scope.deletePerson = function(personId){
$http.delete('person/'+personId).success(function(response){
$scope.deleteResponseStatus = response.status;
}).error(function(){
//handle error
})
}
})
})();
Html
<html ng-app="personApp">
<body ng-controller=""personCtr>
<input type="submit" ng-click="getPersons()"/>
<input type="submit" ng-click="deletePerson(somePersonIdFromTableOrSomething)"
</body>
</html>
Hope it will help, not tested but generally that is the flow..send request to controller with person id, find it in database and delete it
You need to attack the issues individually. Try testing your rest service alone. Use POSTMAN or any other REST Client (https://addons.mozilla/en-US/firefox/addon/restclient/) and test if the service is behaving accordingly. Only when that's successful, check on the Javascript client (AngularJS code) and see if the request (headers, params and body) is the same as the one generated by the REST client.
you can call java method or service in angularjs controller this way:
app.controller('personCtrl',['$scope', '$http', function($scope, $http){
$scope.firstName = "John";
$scope.personList = [];
$scope.typelistload = function() {
$http.get(
'http://localhost:8080/SpringMVCHibernate/Person/getPersonList'
).success(function(data) {
$scope.personList = data;
}).error(function() {
ngToast.danger( "Some problem in Listing:");
});
};
}]);
本文标签: javascriptAngularjs calling java functionsStack Overflow
版权声明:本文标题:javascript - Angularjs calling java functions - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741525859a2383461.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论