Yogesh Doke
Yogesh Doke

Reputation: 1726

can't delete the item from the database with action on the form with ng-submit="controller.delete()

I am developing a new library management software with spring boot,angular js, and MongoDB as backend. I want to perform crud operation on MongoDB with that application and for that I referring some open source project with that I can perform create and read operations successfully but can't perform delete and update operations so how can perform I also made some changes for delete update but can't perform with that so tell me the changes have to perform in order to perform delete.i added this as my own in mybooks.html but element is not deleting.

<td><form ng-submit="controller.delete()">
  <div class="form-group">
            <input type="submit" class="btn btn-default btn-lg" value="Delete">
        </div>
</form></td>

bookrestcontroller.java

package com.sezin.controller;

import com.sezin.model.Book;
import com.sezin.repository.BookRepository;
import com.sezin.repository.UserAccountRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.condition.RequestConditionHolder;

import java.util.List;

/**
 * Created by sezin on 3/23/16.
 */
@RestController
@RequestMapping("/api/books")
public class BookRestController {

    @Autowired
    BookRepository repository;

    @Autowired
    UserAccountRepository userAccountRepository;

    @RequestMapping(method = RequestMethod.GET)
    public List<Book> getAllBooks(){
        return repository.findAll();
    }

    @RequestMapping(value = "/getByTitle/{title}", method = RequestMethod.GET)
    public Book getBookByTitle(@PathVariable String title){
        return repository.findByTitle(title);
    }

    @RequestMapping(value = "/getByAuthor/{author}", method = RequestMethod.GET)
    public List<Book> getBooksByAuthor(@PathVariable String author){
        return repository.findByAuthor(author);
    }

    @RequestMapping(value ="/getAll/{userName}", method = RequestMethod.GET)
    public List<Book> getBooksByUserName(@PathVariable String userName){
        return repository.findByUserName(userName);
    }


    @RequestMapping(value ="/add", method = RequestMethod.POST)
    public @ResponseBody Book create(@RequestBody Book book){
        if( userAccountRepository.findByUsername(book.getUserName()) != null &&
                repository.findByTitle(book.getTitle()) == null){
            return repository.save(book);
        }
        else
            return null;

    }

    @RequestMapping(method = RequestMethod.DELETE, value = "{id}")
    public void delete(@PathVariable String id){


        repository.delete(id);



    }

    @RequestMapping(method = RequestMethod.PUT, value = "{id}")
    public Book update(@PathVariable String id, @RequestBody Book book){
        Book updated = repository.findOne(id);
        updated.setAuthor(book.getAuthor());
        updated.setTitle(book.getTitle());
        updated.setYear(book.getyear());
        return repository.save(book);

    }
}

securitycontroller.java

@Override
protected void configure(HttpSecurity http) throws Exception {
   /* http
            .httpBasic()
            .and()
            .authorizeRequests()
            .antMatchers("/index.html", "/home.html", "/login.html", "/", "/register.html", "/account").permitAll()
            .anyRequest().authenticated().and().csrf()
            .csrfTokenRepository(csrfTokenRepository()).and()
            .addFilterAfter(csrfHeaderFilter(), CsrfFilter.class);*/
    http.authorizeRequests().antMatchers("/index.html", "/home.html", "/login.html", "/", "/register.html", "/account", "/api","/delete").permitAll()
            .anyRequest().fullyAuthenticated().and().
            httpBasic().and().
            csrf().disable();

}

mybooks.html

 <table>



  <tr>
    <th>BooK_title</th>
    <th>BooK_author</th>        
    <th>BooK_year</th>
    <th>update</th>
 </tr>
   <tr ng-repeat="message in controller.messages">
    <td>{{message.title}}</td>
    <td>{{message.author}}</td>     
    <td>{{message.year}}</td>
    <td><form ng-submit="controller.delete()">
  <div class="form-group">
            <input type="submit" class="btn btn-default btn-lg" value="Delete">
        </div>
</form></td>
 </tr>


</table>

hello.js

/**
 * Created by sezin on 3/22/16.
 */
angular.module('hello', ['ngRoute', 'ngResource', 'ngCookies'])
    .config(function($routeProvider, $httpProvider){
        $routeProvider.when('/', {
            templateUrl : 'home.html',
            controller : 'home',
            controllerAs: 'controller'
        }).when('/login', {
            templateUrl : 'login.html',
            controller : 'navigation',
            controllerAs: 'controller'
        }).when('/register', {
            templateUrl : 'register.html',
            controller : 'register',
            controllerAs: 'controller'
        }).when('/mybooks', {
            templateUrl : 'mybooks.html',
            controller : 'books',
            controllerAs: 'controller'
        }).otherwise('/'); 

        $httpProvider.defaults.headers.common["X-Requested-With"] = 'XMLHttpRequest';

    })
    .controller('home', function($http, $cookies) {
        var self = this;
        $http.get('/resource/').success(function(data){
            self.greeting = data;

            self.currentUserName = $cookies.get("username");

            //self.messages = [];
            self.saveBook = function(){
                //var BookRecord = $resource('/account/', {username : self.currentUserName});
                //BookRecord.save(self.book);
                var request = {
                    userName: self.currentUserName,
                    title: self.book.title,
                    author: self.book.author,
                    year: self.book.year
                };
                $http.post('api/books/add', request).success(function(data){

                    if(data){
                        self.success = true;
                    } if(data == null){
                        self.success = false;
                    }
                    console.log(data);
                    //self.messages.push({type:'success', msg: 'Book Saved!'});
                }). error(function(err){
                    console.log(err);
                });
            };

        });


    })
    .controller('books', function($http, $cookies){
        var self = this;
        self.messages = [];
        self.currentUserName = $cookies.get("username");
        $http.get('api/books/getAll/' + self.currentUserName).success(function(data){

            self.messages = data;
            console.log(data);
        })

    })
    .controller('navigation', function($rootScope, $http, $location, $cookies) {
        var self = this;
        var authenticate = function(credentials, callback) {
            var headers = credentials ? {authorization: "Basic "
            + btoa(credentials.username + ":" + credentials.password)} :{};

            $http.get('/user/', {headers : headers}).success(function(data){
                if(data.name){
                    $rootScope.authenticated = true;
                    $rootScope.username = data.username;
                    if (typeof callback == "function") {
                        callback() && callback();
                    }

                } else{
                    $rootScope.authenticated = false;
                    if (typeof callback == "function") {
                        callback() && callback();
                    }
                }
            })
        };

        authenticate();
        self.credentials = {};
        self.login = function(){
            authenticate(self.credentials, function () {
                if($rootScope.authenticated){
                    $location.path("/");
                    $rootScope.username = self.credentials.username;
                    $cookies.put("username", $rootScope.username);
                    self.error = false;
                } else{
                    $location.path("/login");
                    self.error = true;
                }

            });
        };

        self.logout = function(){
            $http.post('logout', {}).finally(function(){
                $rootScope.authenticated = false;
                $location.path("/");
            });
        }
    })
    .controller('register', function($resource, $rootScope, $location){
        var self = this;
        self.register = function(){
            var User = $resource('/account');
            User.save(self.user, function(data){
                    self.success = data;


            });
        };

    });

Upvotes: 0

Views: 116

Answers (1)

Anamika Shrivastava
Anamika Shrivastava

Reputation: 713

For performing delete functionality you have to create delete function in books controller , and there through $http service you can delete records from database. I checked your books controller but there i did not find "delete" method which you are calling on ng-submit.

Upvotes: 1

Related Questions