角度js模块中的控制器功能不适用于删除操作

时间:2016-09-30 05:32:55

标签: java angularjs mongodb spring-boot

我正在开发一个新的库管理软件,其中包括spring boot,angular js和MongoDB作为后端。我想在MongoDB上使用该应用程序执行crud操作,为此,我引用了一些开源项目,我可以成功执行创建和读取操作,但不能执行删除和更新操作,所以如何执行我还对删除进行了一些更改更新,但无法执行,所以告诉我必须执行更改才能执行删除。我在mybooks.html中添加了这个我自己的但是元素没有删除。因为在mybooks.html和hello中做了一些更改.js用于删除操作但该元素未删除

<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

  <tr>
      <th>BooK_id</th>
    <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.id}}</td>
    <td>{{message.title}}</td>
    <td>{{message.author}}</td>     
    <td>{{message.year}}</td>
    <td><form ng-submit="remove(message.id)" ng-controller="books">
  <div class="form-group">
            <input type="submit" class="btn btn-default btn-lg" value="Delete">
        </div>
</form></td>
 </tr>

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);
        });

        self.remove = function(messageId){

$http.delete('messageId');


};


})
    .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;


            });
        };

    });

1 个答案:

答案 0 :(得分:0)

将DELETE方法更改为GET,在pathvariable中传递id param,通过它从DB查找实体。然后删除实体。

控制器

import javafx.application.Application;
import javafx.beans.property.SimpleStringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.stage.Stage;

public class TableMCVE extends Application {
    @Override
    public void start(Stage stage) {

        ObservableList<ObservableList<String>> tableData = FXCollections.observableArrayList();
        tableData.add(FXCollections.observableArrayList("Row1Col1", "Row1Col2"));
        tableData.add(FXCollections.observableArrayList("Row2Col1", "Row2Col2"));
        tableData.add(FXCollections.observableArrayList("Row3Col1", "Row3Col2"));

        TableView<ObservableList<String>> table = new TableView<ObservableList<String>>();

        TableColumn<ObservableList<String>, String> col1 = new TableColumn<ObservableList<String>, String>("Col1");
        col1.setCellValueFactory(e -> new SimpleStringProperty(e.getValue().get(0)));

        // Set the cell factory of the column with a custom TableCell to modify its behavior.
        col1.setCellFactory(e -> new TableCell<ObservableList<String>, String>() {
            @Override
            public void updateItem(String item, boolean empty) {
                // Always invoke super constructor.
                super.updateItem(item, empty);

                if (item == null || empty) {
                    setText(null);
                } else {
                    setText(item);

                    // If index is two we set the background color explicitly.
                    if (getIndex() == 2) {
                        this.setStyle("-fx-background-color: green;");
                    }
                }
            }
        });

        TableColumn<ObservableList<String>, String> col2 = new TableColumn<ObservableList<String>, String>("Col2");
        col2.setCellValueFactory(e -> new SimpleStringProperty(e.getValue().get(1)));

        // Set the cell factory of the column with a custom TableCell to modify its behavior.
        col2.setCellFactory(e -> new TableCell<ObservableList<String>, String>() {
            @Override
            public void updateItem(String item, boolean empty) {
                // Always invoke super constructor.
                super.updateItem(item, empty);

                if (item == null || empty) {
                    setText(null);
                } else {
                    setText(item);

                    // If index is zero we set the background color explicitly.
                    if (getIndex() == 0) {
                        this.setStyle("-fx-background-color: blue;");
                    }
                }
            }
        });

        table.getColumns().addAll(col1, col2);
        table.getItems().addAll(tableData);

        stage.setScene(new Scene(table));
        stage.show();
    }

    public static void main(String[] args) {
        launch();
    }
}

JS

@RequestMapping(value="/delete/{id}", method = RequestMethod.GET)
public void delete(@PathVariable String id){
    Book book = repository.findById(id);
    repository.delete(book);
}