我在django中使用ng-resource时遇到了麻烦,因为它总是会删除尾部斜杠。因此,我通过创建自己的资源来关注https://stackoverflow.com/users/192810/misko-hevery指南https://stackoverflow.com/a/11850027。我想问一下我的代码是否是实现错误回调函数的正确方法? IE:我的服务器响应是这样的{错误:"那本书已经存在!"}
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;
});
可以像这样修改创建方法吗?
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
}
);
};