Using the $ q service with angular

I still can’t understand the role of using the $ q service (what exactly will it add) if you want to create a service that should only call one API via http, in this situation I don’t know why I shouldn’t just do the following (without using $ q):

this.getMovie = function(movie) {
  return $http.get('/api/v1/movies/' + movie)
    .then(
    function(response) {
      return {
        title: response.data.title,
        cost: response.data.price
      });
    },
    function(httpError) {
      // translate the error
      throw httpError.status + " : " +
        httpError.data;
    });
};
+4
source share
4 answers

A very good question, and very few people value the answer.

Consider this:

this.getMovie = function(movie) {
  return $http.get('/api/v1/movies/' + movie);
};

Great code, but the following rules apply:

$http 2xx . . . , HEAD, -.

HEAD /book/fred, 200 , fred. , fred, , 200. $q . :

var defer = $q.defer();
$http.head('/book/fred').then(function(response) {
    // 2xx response so reject because its not unique
    defer.reject(response);
}).catch(function(failResponse) {
    defer.resolve(failResponse);
});
return defer.promise;

$q , .

, $q . , , , .

, $q, .

var a = 5;
var b = 10;
var defer = $q.defer();
var resolve(a+b);
return defer.promise;

Bosh, , .

, .

+4

AngularJS, $http, $timeout, $resource .. $q promises. $q. , , $q.defer , " " ?.

$q, .

$q.all promises.

var promise1 = $http.get(url1);
var promise2 = $http.get(url2);

$q.all([promise1, promise2]).then( responseArray ) {
    $scope.data1 = responseArray[0].data;
    $scope.data2 = responseArray[1].data;
}).catch( function ( firstError ) {
    console.log(firstError.status)
});

.catch . .then. $q.defer . . Angular $q.

$q.when .

 var promise = $q.when(ambiguousAPI(arg1));

$q.when $q, ambiguousAPI , $q .

.then , promises. , ( ), / promises . API. 1

: $q , (, $http, $timeout, $resource ..), promises $q.

+2

$http . , , URL-, $scope .

   $http("your url").then(function(response){
      //This is the success callback
      $scope.movies = response.data;
      });
0

In this case, of course, you do not need, because $http.gethe returns the promise. But, for example, if you make an asynchronous call only under certain conditions, this is useful

function acyncService () {
  if (dataLoaded) return $q.resolve(data);
  return $http.get('path/to/load/data');
}

In this case, even if you are not making an asynchronous call, you can still use

acyncService().then(function(data){
  console.log(data);
});

This is just one of many examples. Also useful $q promiseswhen you are performing asynchronous requests with other libraries, for example AWS SDK.

0
source

All Articles