angular then catch success error from services - angularjs

I'm afraid I may have gone down the rabbit hole of recursive promises.
I have a service that handles my api. (It's got an extra layer of promise so that I could switch back to a local json if the api went offline. (Not sure how necessary it is anymore) - mayte I should eliminate it for simplicity).
Then I've got the promised async call in my controller.
This all works great as long as I get the data I expect, but it doesn't handle errors very well. When I get 400's and 500's, it doesn't send the error message to the user via toastr.
Sadly, this is not a fully-compliant RESTful api. The 400 error I get back is simply
{"Message":"No packages found"}
I don't really get how to get this to behave as it should, and replace success/error with then/catch (as per Angular best practice).
Here is a typical service call:
var _getPackagesPage = function (options) {
var pageSize = options.data.pageSize;
var page = options.data.page -1;
return $q (function(resolve, reject) {
switch (dataSource) {
case 'api'://staging - live api data
return $http({
method: 'get',
url: serviceBase + 'api/Packages?pageSize=' + pageSize + '&page=' + page
}).then(function(results) {
resolve(results);
});
break;
default: // dev - local json
$.getJSON('Content/data/Packages.json', function (json) {
var pageSize = options.data.pageSize;
var page = options.data.page;
var newjson = json.splice(page*pageSize,pageSize);
resolve(newjson);
});
}
});
};
and a typical call in a controller:
(options is the data object handed back to my data grid (Kendo))
vm.getPackages = function(options) {
return packagesService.getPackagesPage (options)
.then(function(results) {
options.success(results.data.Items);
})
.catch(function(error) {
options.error(error);
toastr.error(error.Message);
});
};
How can I clean this up?
[ UPDATE ] Attempted fix per Answer 1, below
Service:
var _getOrdersPage = function (options) {
var deff = $q.defer();
var pageSize = options.data.pageSize;
var page = options.data.page -1;
return $http({
method: 'get',
url: serviceBase + 'api/Packages?pageSize=' + pageSize + '&page=' + page
})
.then(
function(results) {
deff.resolve(results);
},
function(ex){
deff.reject(ex);
});
return deff.promise;
};
Controller:
vm.getOrders = function (options) {
return ordersService.getOrdersPage (options)
.then(function(results) {
console.log("results!");
console.log(results);
})
.catch(function(error) {
console.log("error!");
console.log(error);
});
};
results in:
GET http://< myURL >/api/Packages?pageSize=20&page=0 400 (Bad Request)
results!
undefined

I'm removing the switch case for brevity.
var _getPackagesPage = function (options) {
var pageSize = options.data.pageSize;
var page = options.data.page -1;
var deff = $q.defer();
$http({
method: 'get',
url: serviceBase + 'api/Packages?pageSize=' + pageSize + '&page=' + page
}).then(
function(results) {
deff.resolve(results);
},
function(ex){
deff.reject(ex);
});
return deff.promise;
};
Controller
vm.getOrders = function (options) {
return ordersService.getOrdersPage (options)
.then(
function(results) {
console.log("results!");
console.log(results);
},
function(error) {
console.log("error!");
console.log(error);
});
};
If you dont have any logic inside your service, then you could return the $http itself as $http inturn is a promise:
var _getPackagesPage = function (options) {
var pageSize = options.data.pageSize;
var page = options.data.page -1;
return $http({
method: 'get',
url: serviceBase + 'api/Packages?pageSize=' + pageSize + '&page=' + page
});
};

You have too many returns in your service. The second one is not called.
You don't need to create a promise manually since $http returns apromise.
You're not returning data from your service.
var _getOrdersPage = function(options) {
var pageSize = options.data.pageSize;
var page = options.data.page -1;
return $http({
method: 'get',
url: serviceBase + 'api/Packages?pageSize=' + pageSize + '&page=' + page
})
.then(
function(results) {
return results;
},
function(ex){
return ex;
});
}
Your controller is fine, you can use catch() or pass an error callback.
Example:
function myService($http) {
this.getData = function(url) {
return $http.get(url).
then(function(response) {
return response.data;
}, function(error) {
return error;
});
}
};
function MyController(myService) {
var vm = this;
vm.result = [];
vm.apiUrl = "https://randomuser.me/api/";
myService.getData(vm.apiUrl).then(function (data) {
vm.result = data;
},
function(error) {
console.log(error);
});
};
angular.module('myApp', []);
angular
.module('myApp')
.service('myService', myService)
.controller('MyController', MyController);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
<div ng-app="myApp">
<div ng-controller="MyController as ctrl">
{{ ctrl.result }}
</div>
</div>

Related

Delay $http.get call without affecting angularjs promise

Please note that I already read all the StackOverflow questions that are somewhat related to my questions but none of these really answer my question. Please don't mark this as duplicate without fully understanding my question.
Here's my concern:
I would like to delay angularJS $http.get call without affecting the angular promise. Right now the code below throws a "angular-1.3.15.js:11655 TypeError: Cannot read property 'then' of undefined" in this line:
updatedPromise = promise.then(function(price)
Here's my partial code:
MyAPP.service('FirstService', ['$q','$http', 'Constants', 'SecondService', 'UtilityService', function($q, $http, Constants, SecondService, UtilityService) {
var self = this;
var processFunction = function(AnArray) {
var updatedPromise;
var promises=[];
angular.forEach(AnArray, function(itemObj, index)
{
var totalWorth = "";
if(itemObj.name != "")
{
var promise = SecondService.getPrice(itemObj.name);
updatedPromise = promise.then(function(price){
itemObj.price = price;
return itemObj;
}, function(error){
console.log('[+] Retrieving price has an error: ', error);
});
promises.push(updatedPromise);
}
else
{
console.log("Error!");
}
});
return $q.all(promises);
};
);
MyAPP.service('SecondService', ['$timeout','$http', 'Constants', function($timeout, $http, Constants) {
var self = this;
var URL = "/getPrice";
self.getPrice = function(itemName){
$timeout(function(){
var promise;
promise = $http({
url: URL,
method: 'POST',
data: {_itemName : itemName},
headers: {'Content-Type': 'application/json'}
}).then(function(response) {
return response.data;
}, function(response) {
console.log("Response: " + response.data);
return response.data;
});
return promise;
}, 3500);
console.log("[-]getPrice");
};
}]);
Please note that the processFunction should really return an array of promises because this is needed in other functions.
Your help will be highly appreciated!
Let me know for further questions/clarifications.
Thanks!
$timeout returns a promise, so you can return that, and then return the promise from $http:
self.getPrice = function (itemName) {
return $timeout(3500).then(function () {
return $http({
url: URL,
method: 'POST',
data: { _itemName: itemName },
headers: { 'Content-Type': 'application/json' }
});
}).then(function (response) {
return response.data;
}, function (response) {
console.log("Response: " + response.data);
return response.data;
});
};

Ionic. Using $http giving error Cannot read property 'protocol' of undefined

This question is related to another one.
Before I did added $ionicPlatform, my service working just fine, but now there is something wrong with $http.
Here is example of injectables:
(function () {
"use strict";
angular.module('service', ['ionic'])
.service('BBNService', ["$http", "$localStorage", "$ionicPlatform",
function ($http, $localStorage, $ionicPlatform) {
And using of $http and $ionicPlatform
this.tips = function () {
var url;
$ionicPlatform.ready(function () {
if (window.Connection) {
if (navigator.connection.type == Connection.CELL_4G || navigator.connection.type == Connection.WIFI) {
if (this.getDayId = 0)//If Sunday - retrieve updated tips
url = this.host + "/tips/";
else
url = "data/tips.json";//If not - use saved data
}
}
});
var request = $http({
method: "GET",
url: url
}).then(
function mySucces(response) {
return response.data;
},
function myError(response) {
return response.data;
});
return request;
};
You need to send back the promise, doing a return response.data is not gonna work.
var deferred = $q.defer();
var request = $http({
method: "GET",
url: url
}).then(
function mySucces(response) {
deferred.resolve(response.data);
},
function myError(response) {
deferred.reject(response.data);
});
return deferred.promise;
And at the place where you consume this service:
BBNService.tips().then(
function(data) { //success call back with data },
function(data) { //error call back with data }
);
Please let me know if you need more explanation on using $q; always happy to give more details.

How to convert $http request into $resource request in angularjs

I have this http request, working fine.
Controller
$scope.removeRow = function (od){
var temp = "order_id=" + od.order_id + "&product_id=" + od.product_id + "&variant_id=" + od.varient_id;
var req = $http({
method: 'POST',
url: 'http://<domain name>/api2/v1/delete_item_in_order',
data: temp,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
});
req.then(
function (response) {
alert('success')
},
function (error) {
//$scope.details = response.data;
alert(error.message);
}
);
}
Service code to get resource object:
sampleApp.factory('Order', function ($resource) {
return $resource('http://<domain name>/api2/v1/orders/:id', {id: '#_id'}, {
'get': {method:'GET'}
});
});
Question
How to add custom method removeRow in Order service, such that I can use $resource instead of $http in $scope.removeRow() in controller?
Rather than returning a single function, you can return an object with as many methods in following way
sampleApp.factory('Order', function ($resource) {
var removeRow = function() {console.log()};
var getResource = function)() {
$resource('http://<domain name>/api2/v1/orders/:id', {id: '#_id'}, { 'get': {method:'GET'} });
}
return { removeRow : removeRow,
getResource : getResource
}
});
There is no need to specify the get method inside $resource, this is already predefined.
Factory:
sampleApp.factory('Order', function ($resource) {
return $resource('http://<domain name>/api2/v1/orders/:id', {id: '#_id'}, null}).$promise;
});
Calling Method:
$scope.removeRow = function (od){
var temp = "order_id=" + od.order_id + "&product_id=" + od.product_id + "&variant_id=" + od.varient_id;
Order.save(temp).then(function(result){
alert('success');
}, function(err){
alert(err.message);
});
};

$http.get keeps launching new queries

I'm encountering a weird issue in my AngularJS app. It's supposed to access a number of values from a cookie 'login', pass those values to an API endpoint and then return the API response.
This works fine, except it keeps launching new GET queries continuously every 500ms. This results in an unending stream of the console error: "Error: 10 $digest() iterations reached. Aborting!" and forcing me to kill it manually.
Where is this weird behavior coming from, and how can I limit it to just 1 run?
workbooks.html
<body>
<div>This is the workbooks view.</div>
<span>{{callQueryWorkbooksForUser()}}</span>
<section ui-view>{{response}}</section>
</body>
workbooks.controller.js
'use strict';
(function() {
class WorkbooksComponent {
constructor($scope, $http, $cookies) {
$scope.callQueryWorkbooksForUser = function() {
var login = JSON.parse($cookies.get('login'))
var auth_token = login.authentication_token;
var siteid = login.site_id;
var userid = login.user_id;
$http({
method: 'GET',
url: '/api/sites/' + siteid + '/users/' + userid + '/workbooks',
params: {
auth_token: auth_token
}
}).then(function successCallback(response) {
$scope.response = response.data
}, function errorCallback(response) {
$scope.response = 'Server error'
});
};
}
}
angular.module('orbitApp')
.component('workbooks', {
templateUrl: 'app/workbooks/workbooks.html',
controller: WorkbooksComponent
});
})();
Make the http request in init block of your controller.
class WorkbooksComponent {
constructor($scope, $http, $cookies) {
this.$onInit = function() {
var login = JSON.parse($cookies.get('login'))
var auth_token = login.authentication_token;
var siteid = login.site_id;
var userid = login.user_id;
$http({
method: 'GET',
url: '/api/sites/' + siteid + '/users/' + userid + '/workbooks',
params: {
auth_token: auth_token
}
}).then(function successCallback(response) {
$scope.response = response.data
}, function errorCallback(response) {
$scope.response = 'Server error'
});
};
}
}

How to do error handling when fetching data in angularjs service

This code fetches categories and give them to controller.
sampleApp.factory('SCService', function($http, $q) {
var SuperCategories = [];
var SCService = {};
SCService.GetSuperCategories = function() {
var req = {
method: 'POST',
url: SuperCategoryURL,
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
data: "action=GET"
};
if ( SuperCategories.length == 0 ) {
return $http(req).then(function (response) {
SuperCategories = response.data;
return SuperCategories;
});
}else {
return $q.when(SuperCategories);
}
}
return SCService;
});
I think code is perfect until there is no error in http request.
My query is how to do error handling (try catch or something like that), in case if server have some issue or may be cgi-script have some issue and not able to server the request.
Angular promises use a method catch for that.
return $http(req).then(function (response) {
SuperCategories = response.data;
return SuperCategories;
}).catch(function(error) {
// Do what you want here
});
You should use also finally :
return $http(req).then(function (response) {
SuperCategories = response.data;
return SuperCategories;
}).catch(function(error) {
// Do what you want here
}).finally(function() {
// Always executed. Clean up variables, call a callback, etc...
});
Write like
return $http(req).then(function (response) {
//success callback
},
function(){
//Failure callback
});
Use callback methods from controller Like
Controller.js
service.GetSuperCategories(function (data) {console.log('success'},function (error){console.log('error'});
service.js
sampleApp.factory('SCService', function($http, $q) {
var SuperCategories = [];
var SCService = {};
SCService.GetSuperCategories = function(successMethod,errorMethod) {
var req = {
method: 'POST',
url: SuperCategoryURL,
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
data: "action=GET"
};
return $http(req).then(successMethod(data),
errorMethod(error));
}
return SCService;
});
You can use the .success and .error methods of $http service, as below
$http(req).success(function(data, status, headers){
// success callback: Enters if status = 200
}).error(function(status, headers){
// error callback: enters otherwise
});

Resources