0

Hi Can any one please help me about this service call methods in angular Js.

what is the difference between Success function and Then Function?

Which function is use in which condition

Question
  • 57
  • 3
  • 11
  • 1
    the `httpPromise` is what `$http` returns. So it is in fact what you are asking about. The question linked is a really good answer to your question. – Malkus Aug 19 '14 at 11:26
  • Siva: You are not behaving properly here. You should know that very well. @Malkus has provided a very helpful duplicate link. Before giving "negative to" someone's comment, you "must have a look"... – Andrew Barber Aug 19 '14 at 13:49

2 Answers2

4

As per the documentation: https://docs.angularjs.org/api/ng/service/$http

The .then() function is the standard way to register callbacks for when a promise has been resolved - see https://docs.angularjs.org/api/ng/service/$q for angular's implementation of promises.

The promise returned by $http is a promise for a Response:

$http.get('http://example.com').then(function successCallback(response) {
   response.data, response.status, and so on
})

Oftentimes, all you need from the Response is just the data. The callbacks registered via .success() will receive just data:

$http.get('http://example.com').success(function successCallback(data) {
   data.??? depending on what you return
})
Sacho
  • 2,169
  • 1
  • 14
  • 13
  • So, why then use q service. What is the point if http returns promise which can receive response object. – Vlado Pandžić Apr 14 '15 at 21:21
  • 2
    Well, angular handles many of the async operations for you - you can make ajax requests via `$http`, you can set timers via `$timeout` and `$interval`, which all return promises . But a few examples where you would need `$q` would be: 1) `$q.when(value)` - you already have the value, but want to maintain a consistent return type(e.g. caching). You might also want to compose promises - `$q.all(manypromises)` creates a promise that is resolved when *all of them* are. And of course, any other async operation that you might need to craft a custom deferred for. – Sacho Apr 15 '15 at 06:50
2

In angular.js we have $http and $q , both returns the promise object.

The main difference between $httpPromise and $q.defer().promise is that $http provide you two more function success and error. So you can't use success and error to a function returning $q.defer().promise.

One difference in context of $http is as Sacho explained below.

Community
  • 1
  • 1
Rawat Raman
  • 479
  • 1
  • 5
  • 13