AngularJS what is difference between $http success and then - angularjs

various people use $http different way. say sample 1
$http({
method: 'GET',
url: 'api/book/',
cache: $templateCache
}).
success(function (data, status, headers, config) {
$scope.books = data;
}).
error(function (data, status) {
console.log("Request Failed");
});
here success and error callback is there to notify user. again few people use $http different way like
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;
});
};
here then is using.......is it promise sample ? why people would then instead of success ? what is the advantage of then ?
what is the meaning of promise and what promise does ?
when to use promise in angular ?

Per angular DOCS, looks like 1.4.4 is the first version to have the notice(see below).
Deprecation Notice
The $http legacy promise methods success and error have been
deprecated. Use the standard then method instead. If
$httpProvider.useLegacyPromiseExtensions is set to false then these
methods will throw $http/legacy error.
From the docs, the new preferred angular way to do all $http requests.(code from angular docs)
General usage
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.
// Simple GET request example :
$http.get('/someUrl').
then(function(response) {
// this callback will be called asynchronously
// when the response is available
}, function(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
// Simple POST request example (passing data) :
$http.post('/someUrl', {
msg: 'hello word!'
}).
then(function(response) {
// this callback will be called asynchronously
// when the response is available
}, function(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
SO resource
SO resource

Related

AngularJS access $http on onNotification event PushNotification cordova plugin

I'm using the plugin https://github.com/phonegap-build/PushPlugin/ with Angular 1.3 and I need to send the regid to server when receive "registered" event.
The problem is that I don't have $http object to call my server on this context. How can I achieve that, please?
function onNotification(e){
if(e.event == "registered"){
var req = {
method: "POST",
url: "http://myurl.com/?var="+e.regid
};
$http(req).success(function(data){
alert(data);
});
}
}
I just learned how to inject $http into the event method:
$http = angular.injector(["ng"]).get("$http");
Change $http call as follows, .success is deprecated.
$http({
method: "POST",
url: "http://myurl.com/?var="+e.regid
}).then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
alert(response);
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
Ref. : https://docs.angularjs.org/api/ng/service/$http
Regards.

Creating custom header for $http in AngularJs

In my controller i want send a request using get method if $http, in that get method i want to send the sessionID in headers. Below am giving the code snippet please check.
this.surveyList = function () {
//return session;
return $http.get('http://op.1pt.mobi/V3.0/api/Survey/Surveys', {headers: { 'sessionID': $scope.sessionid}})
.then(function(response){
return response.data;
}, function(error){
return error;
});
}
but this is not working when i send this vale in backend they getting null.
So how to resolve this.
we have a issue where the api is getting called twice from angular , however it works only once when called with the POSTMAN. And here with the custom header passed to the api, the action is called twice. What could be the reason for it?
Try in this way,
$http({
method: 'GET',
url: 'http://op.1pt.mobi/V3.0/api/Survey/Surveys',
headers: {
'sessionId': $scope.sessionid
}
}).then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
}, function errorCallback(response) {
// called asynchronously if an error occurs,
// or server returns response with an error status.
});

$http.get doesn't work with REST model using then() function

As you guys know, Angular recently deprecated the http.get.success,error functions. So this kind of calls are not recommended in your controller anymore:
$http.get("/myurl").success(function(data){
myctrl.myobj = data;
}));
Rather, this kind of calls are to be used:
$http.get("/myurl").then(
function(data) {
myctrl.myobj = data;
},
function(error) {
...
}
Problem is, simple Spring REST models aren't working with this new code. I recently downloaded a sample code with the above old success function and a REST model like this:
#RequestMapping("/resource")
public Map<String,Object> home() {
Map<String,Object> model = new HashMap<String,Object>();
model.put("id", UUID.randomUUID().toString());
model.put("content", "Hello World");
return model;
}
This should return a map like {id:<someid>, content:"Hello World"} for the $http.get() call, but it receives nothing - the view is blank.
How can I resolve this issue?
The first (of four) argument passed to success() is the data (i.e. body) of the response.
But the first (and unique) argument passed to then() is not the data. It's the full HTTP response, containing the data, the headers, the status, the config.
So what you actually need is
$http.get("/myurl").then(
function(response) {
myctrl.myobj = response.data;
},
function(error) {
...
});
The expectation of the result is different. Its the response and not the data object directly.
documentation says :
// Simple GET request example:
$http({
method: 'GET',
url: '/someUrl'
}).then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
Properties of the response are
data – {string|Object} – The response body transformed with the transform functions.
status – {number} – HTTP status code of the response.
headers – {function([headerName])} – Header getter function.
config – {Object} – The configuration object that was used to generate the request.
statusText – {string} – HTTP status text of the response.
As the data object is required,
Please convert the code as
$http.get("/resource").then(
function(response) {
myctrl.myobj = response.data;
});
then must be return a new promise so you should handle it with defers.
var myApp = angular.module('myApp', []);
myApp.factory('modelFromFactory', function($q) {
return {
getModel: function(data) {
var deferred = $q.defer();
var items = [];
items.push({"id":"f77e3886-976b-4f38-b84d-ae4d322759d4","content":"Hello World"});
deferred.resolve(items);
return deferred.promise;
}
};
});
function MyCtrl($scope, modelFromFactory) {
modelFromFactory.getModel()
.then(function(data){
$scope.model = data;
})
}
Here is working fiddle -> https://jsfiddle.net/o16kg9p4/7/

Same $http.get request automatically trigger success callback before processing in second call

I'm trying to build a simple hybrid app with Ionic Framework.
I want to create an inifite scroll system, so I have:
.controller('DiscoverCtrl', function (uris, $scope, $cordovaToast, $http, $ionicLoading, $ionicSideMenuDelegate, $ionicScrollDelegate, $ionicPopover, localStorage, $ionicPlatform, helpers) {
var loadCircuits = function(page_to_load) {
var page_to_load = page_to_load || 1
$http.get(uris({pagination: true, per_page: 10, page: page_to_load}).circuits.discover, {timeout: 20000})
.success(function(response, status, headers, config) {
alert("success")
angular.forEach(response.circuits, function (circuit) {
$scope.cards.push(circuit);
// console.log(circuit.description)
});
$scope.next_page = response.pagination.next_page;
})
.error(function(data, status, headers, config) {
$ionicLoading.hide();
// called asynchronously if an error occurs
// or server returns response with an error status.
$cordovaToast.showLongBottom('Sory, request failed:' + status).then(function(success) {
// success
}, function (error) {
// error
});
});
}
loadCircuits();
// Load more data
$scope.loadMoreData = function() {
alert("loadMore")
loadCircuits($scope.next_page);
}
});
And:
<ion-infinite-scroll
immediate-check="false"
on-infinite="loadMoreData()"
distance="1%">
</ion-infinite-scroll>
But I'm facing the following issue:
The first time I call loadCircuits(), the success callback is triggered normally. The second time (meaning when we call $scope.loadMoreData(), the success callback is triggered before actually performing the $http.get request... And I don't understand why.
Angular Version: 1.4.3.
Thanks for your help.
$http calls are cached if they are made for same url with same parameters, so in your case it is possible that parameters haven't changed, I'd consider logging the next page.
You can also enforce not to cache with
cache: false
In $http request config

How to know from controller if http.post().then... was successful?

I have a controller which uses the following line to post data to server through a factory called SendDataFactory:
SendDataFactory.sendToWebService(dataToSend)
And my factory SendDataFactory looks like this:
angular
.module('az-app')
.factory('SendDataFactory', function ($http, $q) {
var SendData = {};
/**
* Sends data to server and
*/
SendData.sendToWebService = function (dataToSend) {
var url = "example.com/url-to-post";
var deferred = $q.defer();
$http.post(url, dataToSend)
//SUCCESS: this callback will be called asynchronously when the response is available
.then(function (response) {
console.log("Successful: response from submitting data to server was: " + response);
deferred.resolve({
data: data
});
},
//ERROR: called asynchronously if an error occurs or server returns response with an error status.
function (response) {
console.log("Error: response from submitting data to server was: " + response);
deferred.resolve({
data: data
});
}
);
return deferred.promise;
}
return SendData;
});
I have seen some examples in here and the internet with
$http.post().success...
but I want to use
$http.post().then...
since angular documentation says:
The $http legacy promise methods success and error have been deprecated. Use the standard then method instead. If $httpProvider.useLegacyPromiseExtensions is set to false then these methods will throw $http/legacy error.
What I need:
Now in my controller I need to check if the $http.post().then... was successful or not and then do something based on success or fail. How can I achieve this?
I think this is what you meant:
$http.post(url, dataToSend)
//SUCCESS: this callback will be called asynchronously when the response is available
.then(function (response) {
console.log("Successful: response from submitting data to server was: " + response);
deferred.resolve({
data: response //RETURNING RESPONSE SINCE `DATA` IS NOT DEFINED
});
},
//ERROR: called asynchronously if an error occurs or server returns response with an error status.
function (response) {
console.log("Error: response from submitting data to server was: " + response);
//USING THE PROMISE REJECT FUNC TO CATCH ERRORS
deferred.reject({
data: response //RETURNING RESPONSE SINCE `DATA` IS NOT DEFINED
});
}
);
return deferred.promise;
}
In your controller you now can use:
SendDataFactory.sendToWebService(dataToSend)
.then(function(data) { /* do what you want */ })
.catch(function(err) { /* do what you want with the `err` */ });
Reject the promise instead of resolving it when it is rejected by $http.
/**
* Sends data to server and
*/
SendData.sendToWebService = function (dataToSend) {
var url = "example.com/url-to-post";
var deferred = $q.defer();
$http.post(url, dataToSend)
//SUCCESS: this callback will be called asynchronously when the response is available
.then(function (response) {
console.log("Successful: response from submitting data to server was: " + response);
deferred.resolve(response.data); // Resolving using response.data, as data was not defined.
},
//ERROR: called asynchronously if an error occurs or server returns response with an error status.
function (response) {
console.log("Error: response from submitting data to server was: " + response);
deferred.reject(response.data); // Rejecting using response.data, as data was not defined.
}
);
return deferred.promise;
}
You can then call it from your controller the same way as you handle the callback in the service using then.
Since $http returns a promise, it can be simplified further though using promise chaining. This way there is no need to use an extra deferred object.
/**
* Sends data to server and
*/
SendData.sendToWebService = function (dataToSend) {
var url = "example.com/url-to-post";
return $http.post(url, dataToSend)
//SUCCESS: this callback will be called asynchronously when the response is available
.then(function (response) {
console.log("Successful: response from submitting data to server was: " + response);
return response.data; // Resolving using response.data, as data was not defined.
},
//ERROR: called asynchronously if an error occurs or server returns response with an error status.
function (response) {
console.log("Error: response from submitting data to server was: " + response);
return $q.reject(response.data); // Rejecting using response.data, as data was not defined.
}
);
}

Resources