angularjsangularjs-http

Return Angular promise at client side, without server round-trip


I'm using Angular xeditable for my project.

I'm using Angular xeditable row component for my grid.

As I know, if I use

 return  $http.post('api/students',model).sucess(function(data) {

 })
.error(function(data) {
 }) ;

As I know, what happens - above code will call students CONTROLLER post method web api. If it returns OK, success will be executed and returned else error will be executed and returned.

But my question is - can I call .error call from JavaScript itself?

Let's say:

 if( textbox == "") 

       return $http.post().error().......
  
  else

        return $http.post().sucess()....

Why I want something like this?

Because for single textbox I have to make server trip to check whether it is empty or not. If it is not empty, I return OK() else I return (let's say) NotFound().

OK will execute success call, NotFound will execute error call.

So at JS side if I check whether string is empty or not. If empty forcefully (without server trip) I want to 'return' .error callback. Is it possible?

$http.post will make server trip, I know that. But what at client side if I want to return error promise forcefully?


Solution

  • You can use the $q library to rejected promise.

    To return an error promise:

    angular.module(....)
      .service('myService', ['$q', '$http', ....,
         function($q, $http, ....) {
            ...
            this.myFunction = function(data) {
    
              if (isValid(data)) {
                return $http.post(....);
              } else {
                return $q.reject("rejection message");
              }
    
            };
            ...
         }]);