1

我在 django 中使用 ng-resource 时遇到了麻烦,因为它总是删除尾部斜杠。因此,我通过创建自己的资源来遵循https://stackoverflow.com/users/192810/misko-hevery指南https://stackoverflow.com/a/11850027 。我想问一下我的代码是否是实现错误回调函数的正确方法?IE:我的服务器响应如下 {err : "that book already exists!"}

angular.module('myApp').factory('Book', function($http) {
  var Book = function(data) {
    angular.extend(this, data);
  }

  Book.get = function(id) {
    return $http.get('/Book/' + id).then(function(response) {
      return new Book(response.data);
    });
  };

  Book.prototype.create = function() {
    var book = this;
    return $http.post('/Book/', book).then(function(response) {
      book.id = response.data.id;
      return book;
    });
  }

  return Book;
});

像这样修改create方法可以吗?

Book.prototype.create = function() {
    var book = this;
    return $http.post('/Book/', book).then(function(response) {
      book.id = response.data.id;
      return book;
    }, function(response){
      book.err = response.err
      return book;
    });
  }

我这样修改控制器

var AppController = function($scope, Book) {
  $scope.err = ""
  // to create a Book
  var book = new Book();
  book.name = 'AngularJS in nutshell';
  book.create().then(function(){
    //check error, if exists pass the error message to scope
    if(typeof book.err !== "undefined"){
      $scope.err = book.err
    }
  );

};
4

0 回答 0