Search code examples
javascriptangularjspromiseangularjs-service

Do Angular JS $http promises to behave like true $q promises?


I'm aware that Angular can handle promises from within controllers. For example:

function MyCtrl($scope) {
  $scope.myvar = getDeferredPromise();
}

The main angular digest loop handles this gracefully, assigning whatever value the deferred function finally returns later to myvar.

However, although the $http.get() method returns a promise, I cannot get it to work in this way. For example:

function MyCtrl($scope, $http) {
  $scope.myvar = $http.get('/url');
} 

The 'promise' the get method returns has a success method which takes a function that is assigned the data that one would wish to assign to myvar.

However, it also has a then method - but that is given the entire response object - not just that data part! This is what seems to end up getting assigned to myvar!

This fiddle may help: http://jsfiddle.net/QKnNC/1/

Am I doing something wrong here? Or is this somehow 'by design'?


Solution

  • ng.$http

    The $http service is a function which takes a single argument — a configuration object — that is used to generate an HTTP request and returns a promise with two $http specific methods: success and error.

    $http returns a promise, so you need to chain then to get the data.

    IPService.getV1().then(function (response) {
        console.log(response)
        $scope.value1 = response.data;
    });