I'm having trouble while using ng-resource in django because it always removes the trailing slash. So I follow https://stackoverflow.com/users/192810/misko-hevery guide https://stackoverflow.com/a/11850027 by creating my own resource. I wanna ask if my code is the proper way to implement error callback function? IE: my response from server like this {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;
});
Is is ok to modify the create method like this?
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;
});
}
I modify the controller like this
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
}
);
};