Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS Promises - Simulate http promises

I wonder how to simulate a promise $http when I know that the request will fail on the server-side. Here is my code:

if ( !ng.isString(email) ) {
    var promise = $q.defer().promise;
    $q.reject();

    return promise;
}

return $http( {
         method : "PUT",
         url : "//localhost/update" ,
         data : { data: email } 
})

// Success handler
.success(response){ return response})

// Error handler
.error(errorMsg){ return errorMsg});
like image 617
Frank6 Avatar asked Aug 14 '13 22:08

Frank6


1 Answers

You can use resolve and reject to control the flow of your data:

Let's say you have a service like this:

var app = angular.module("mymodule.services", []);

app.factory("HttpRequest", ['$q', '$http', function(q, http) {
  var deferredData = q.defer();

  http.get('http://your-server.local/data.json').success(function(data) {
    //success, resolve your promise here
    deferredData.resolve(data);
  }).error(function(err) {
    //error, use reject here
    deferredData.reject(err);
  });

  return {
    get: function() {
      return deferredData.promise;
    }
  };
}]);

The service can then be used as such:

var app = angular.module("mymodule.controllers", ['mymodule.services']);

app.controller("MyCtrl", ['HttpRequest', '$scope', function(res, scope) {
  //the "then"-method of promises takes two functions as arguments, a success and an erro callback
  res.get().then(function(data) {
    //first one is the success callback
    scope.data = data;
  },
  function(err) {
    scope.err = err; 
  }); 
}]);

You can handle the error in the second callback.

like image 161
Florian Avatar answered Nov 02 '22 23:11

Florian