【问题标题】:controller function in angular js module doesn't work for the delete operationangular js模块中的控制器功能不适用于删除操作
【发布时间】:2016-09-30 05:32:55
【问题描述】:

我正在开发一个新的库管理软件,它使用 spring boot、angular js 和 MongoDB 作为后端。我想使用该应用程序在 MongoDB 上执行 crud 操作,为此我引用了一些开源项目,我可以成功执行创建和读取操作但无法执行删除和更新操作,所以如何执行我还对删除进行了一些更改更新但无法执行,所以告诉我必须执行更改才能执行删除。我在 mybooks.html 中将其添加为我自己的,但该元素没有删除。因为在 mybooks.html 和你好.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);

    }
}

安全控制器.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>

你好.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;


            });
        };

    });

【问题讨论】:

  • $http.delete() 向 URL 发送 DELETE 请求。所以它需要一个 URL 作为参数,而不是硬编码的字符串“messageId”。
  • 我要提供哪个网址请好好分析我在关注GitHub上的开源项目github.com/seziny/WebApp
  • 我对 hello.js 文件和 mybooks.html 中的删除操作做了一些更改

标签: java angularjs mongodb spring-boot


【解决方案1】:

将DELETE方法改为GET,在pathvariable中传递id参数,从DB中通过id找到实体。然后删除实体。

控制器

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

JS

$http.get('api/books/delete/'+yourBookId).success(function(data){

    // success 
}). error(function(err){
    // error
});

【讨论】:

  • 不工作检查 hello.js 文件的删除操作
  • 在对 hello.js 和 mybooks.html 进行了更改以进行删除操作后,我无法登录我的应用程序这是什么问题我正在关注开源项目这里是项目的链接
  • 我可以在+yourbookid处添加messageID
  • 你应该在 'yourBookId' 中传递你的 id,比如“api/books/delete/23”(假设 23 是你的 id)。
  • 您在浏览器检查器中遇到的任何异常。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多