Error handling in Angular js - javascript

How to i handle when there is no response from api
service.js
app.factory('dropdownService', function ($http,CD_CONTEXT_VOLTAGE_URL) {
return {
getDropDownData: function (callback) {
$http.get(CD_CONTEXT_VOLTAGE_URL).success(callback);
}
}
});
controller.js
app.controller('loadDropDownController', ['$scope','dropdownService',function($scope,dropdownService) {
getFormData();
function getFormData() {
dropdownService.getDropDownData(function (results) {
$scope.contextlist = results.context;
$scope.cdlst = results.coordinationType;
$scope.voltageList = results.constraintValue;
});
};
}]);
The above code handles only success conditions.Could somebody help me with the code so that i can handle the error condition

If you check angular $http documentation, you will see that $http.get() returns a promise which has an .error() method. That is where you give some function which handles the error for you.
app.factory('dropdownService', function ($http,CD_CONTEXT_VOLTAGE_URL) {
return {
getDropDownData: function (callback) {
$http.get(CD_CONTEXT_VOLTAGE_URL).
success(callback).
error(errorCallback);
}
}
});

In your service.js
app.factory('dropdownService', function ($http,CD_CONTEXT_VOLTAGE_URL) {
return {
getDropDownData: function (callback, errorCallback) {
$http.get(CD_CONTEXT_VOLTAGE_URL)
.success(callback)
.error(errorCallback);
}
}
});
While in your controller.js
app.controller('loadDropDownController', ['$scope','dropdownService',function($scope,dropdownService) {
getFormData();
function getFormData() {
dropdownService.getDropDownData(function (results) {
$scope.contextlist = results.context;
$scope.cdlst = results.coordinationType;
$scope.voltageList = results.constraintValue;
}, function(error){
console.log('Error while getting response from the REST call');
});
};
}]);
This should do the trick.

In your service you can register .error callback() as well along with, .success() call back.
The updated code will be:
service.js
app.factory('dropdownService', function ($http,CD_CONTEXT_VOLTAGE_URL) {
return {
getDropDownData: function (successcallback,errorCallback) {
$http.get(CD_CONTEXT_VOLTAGE_URL)
.success(successcallback)
.error(errorCallback);
}
}
});
controller.js
app.controller('loadDropDownController', ['$scope','dropdownService',function($scope,dropdownService) {
getFormData();
function getFormData() {
dropdownService.getDropDownData(function (results) {
$scope.contextlist = results.context;
$scope.cdlst = results.coordinationType;
$scope.voltageList = results.constraintValue;
},function(){
//do something on error
});
};
}]);

Related

Error in Returning Promise ,Getting Error as .then is not a function in Angular JS

I am getting the error as modifyProduct.then is not a function, I have read through some article and it says because I have not returned any promises, How I can achieve this, Can someone help me
Here I am calling modifyProduct inside executionFromCompany function and then I am using executionFromCompany inside the controller
var app = angular.module('myApp', ["chart.js"]);
app.factory('ProductsService', function($http) {
function getProduct() {
return $http.get('finalmsodetails.json').then(function(response) {
//console.log(response.data);
return response.data;
});
}
function modifyProduct() {
return getProduct().then(function(rawData) {
newtest = rawData;
//console.log('test', newtest.length);
var lightData = rawData.map(function(item) {
// use Object.assign to prevent mutating original object
var newItem = Object.assign({}, item);
var lightExecutions = item.executions.map(function(d) {
var ld = {
id: d.id,
orderId: d.orderId,
executionStatus: d.executionStatus,
executedOn: d.executedOn,
executedBy: d.executedBy,
executedByDisplay: d.executedByDisplay,
};
return ld;
});
newItem.executions = lightExecutions;
return newItem;
});
return lightData;
});
}
function executionFromCompany() {
return modifyProduct.then(function(lightData) {
executionByCompany = $filter('filter')(lightData.executions, function(inputs) {
if ((inputs.executedBy == 'a')) return inputs;
});
console.log(executionByCompany);
return executionByCompany;
});
}
return {
getProduct: getProduct,
modifyProduct: modifyProduct,
executionFromCompany: executionFromCompany
};
});
app.controller('MainCtrl', function($scope, ProductsService) {
ProductsService.executionFromCompany().then(function(value) {
console.log(value);
}, function(err) {
// Here will be if there was an error
})
});
modifyProduct is a function, not an object
change this
modifyProduct.then
to this
modifyProduct().then

how do i get the service response data into the md dialog angularjs?

i have created the custom service like this
app.service('userService', function($http,UrlService) {
return {
init: function(callback) {
$http.get(UrlService.baseUrl +'/api/users/list').then(function(user_response) {
callback(user_response);
});
}
}
})
Inside of my project main controller i have used like this to get the angular material design modal.
$scope.replyComplaint = function(user,complaint_id) {
complaint_id=user._id;
console.log(complaint_id)
$mdDialog.show({
controller: DialogCtrl,
templateUrl: 'submodules/user_management/replydialog.html',
resolve: { complaint_id : function() {return complaint_id;} },
locals: {
users: $scope.users
},
parent: angular.element(document.body),
clickOutsideToClose: true,
})
.then(function(response) {
$scope.response = response;
console.log(response);
}, function() {
//fail
});
};
created another controller for dialog as in the angular material docs as follows
function DialogCtrl($scope, $rootScope, $mdDialog, users,complaintService, UrlService, $http) {
complaintService.init(function(complaint_response) {
$scope.complaints = complaint_response.data;
$scope.getUsers();
});
$scope.getUsers = function(complaint_id) {
console.log(complaint_id);
$scope.hide = function() {
$mdDialog.hide();
};
$scope.cancel = function() {
$mdDialog.cancel();
};
$scope.replyMail = function(complaint_id) {
console.log(complaint_id);
$http.post(UrlService.baseUrl + '/api/complaints/complaint/'+complaint_id , {
complaint: "replyText"
}, $scope)
.then(function(response) {
console.log(name);
$state.reload();
}, function(response) {
console.log(name);
});
}
}
}
Now, i need to get the user_response data in DialogController. if i put console.log('$scope.users') inside of this userservice.init function, i can get the data. but not outside of it. how to get the response data outside of the userService.init function
userService.init(function(user_response) {
$scope.users = user_response.data;
}); //this is added in DialogController
Main intension is to get the user.comlaint_id in the post request of reply mail function . that user.complaint_id is a part of the user_response
Anyone please help me. Thanks
The $http.get call returns a promise, you can just use that.
app.service('userService', function($http,UrlService) {
return {
init: function(callback) {
return $http.get(UrlService.baseUrl +'/api/users/list');
}
}
});
Controller:
function Dialog($scope,$rootScope, $mdDialog,userService,UrlService,$http) {
// console.log(userService.init());
init();
function init() {
userService.init().then(function(response) {
$scope.users = response.data;
});
}
}
This also has the advantage of easier error handling:
function Dialog($scope,$rootScope, $mdDialog,userService,UrlService,$http) {
// console.log(userService.init());
init();
function init() {
userService.init().then(function(response) {
$scope.users = response.data;
}, function(error) {
// handle error
});
}
}
You should read up on angular/javascript promises and their chaining mechanism: angular promises
Here is the solution
userService.init(function(user_response) {
$scope.users = user_response.data;
$scope.init();
});
$scope.init = function() {
You can access $scope.users here
}
Call any method instead of init() in which you require $scope.users

How to pass values between service and controllers

How can one pass values from services to controllers? I have been reading stackoverflow questions regarding this and none of the solutions seem to solve my problem. I am trying to access google spreadsheets using tabletop.js When I console.log from services I can see the values however when I try to access the spreadsheet values from controller I get the following error: chartService.getProperty is not a function
The code for getting URL of the spreadsheet works fine. With get method. Not sure what I am doing wrong here.
Controller
angular.module('myapp')
.controller('piechartCtrl', function (chartService, $scope, config) {
$scope.values = chartService.getProperty();
});
Service.js
angular.module('myapp')
.service('chartService', function(){
return {
getUrl: function init(path) {
Tabletop.init( { key: path,
callback: showInfo,
simpleSheet: true } )
}
}
function showInfo(data, tabletop) {
return{
getProperty: function(){
return data
},
setProperty: function(value){
data = value;
}
}
}
});
This is your service, the only thing i see you returning is the getUrl. so the only thing you will be able to access from the controller is chartService.getUrl function.
service('chartService', function ()
{
return
{
getUrl: function init(path)
{
Tabletop.init({
key: path,
callback: showInfo,
simpleSheet: true
})
}
}
function showInfo(data, tabletop)
{
return
{
getProperty: function ()
{
return data
},
setProperty: function (value)
{
data = value;
}
}
}
});
To Get it working, while I don't think this is the ideal solution it should work...
service('chartService', function ()
{
var returnObject =
{
getUrl: function init(path)
{
Tabletop.init({
key: path,
callback: showInfo,
simpleSheet: true
})
},
resultValue: {}
}
function showInfo(data, tabletop)
{
return
{
getProperty: function ()
{
return data
},
setProperty: function (value)
{
data = value;
returnObject.resultValue = value;
}
}
}
return returnObject
});
then replace chartService.getProperty() with chartService.resultValue although this is in no was synchronous.

sharing $scope.data between 2 different function

getTopicContent.request().finally(function(){
$scope.loader= false;
}).then(function(response){
$scope.threadContent = response.data;
})
$scope.loadPages = function($scope) {
console.log($scope.threadContent.totalPages);
}
It returned threadContent of undefined. getTopicContent is the service, but I expect $scope.threadContent can be shared with $scope.loadPages function?
Since you are loading content asynchronously, you can't expect data to be available in synchronous manner. loadPages function should rely on promis resolution before accessing data. For example you can rewrite you code this way:
function getContent() {
return getTopicContent.request().then(function (response) {
return response.data;
}).finally(function () {
$scope.loader = false;
});
}
$scope.loadPages = function ($scope) {
getContent().then(function(data) {
$scope.threadContent = data;
console.log($scope.threadContent.totalPages);
});
}
Also read this related problem description.

How to write a multiple Aync Function within a Service in AngularJS

Im just starting on AngularJS. I'm not sure how to churn this out. I'm trying to include multiple functions within one service. (I hope this is not against bad practice.)
The following is my working code:
myDataService.async().then(function (d) {
$scope.dbCalls = d.d;
});
My Service:
app.factory('myDataService', function ($http) {
// How do you get this bottom line to work?
// this.getAllCalls = function () {
var myService = {
async: function () {
var promise = $http.post('AngularTest.aspx/FetchCalls', { data: {} }).then(function (response) {
console.log(response);
return response.data;
});
return promise;
}
};
return myService;
//}; <--Commented out for clarity
});
Thanks!
you just return an object with properties from the service, then you are able to call those properties as different service methods
like so:
.service('myService', function() {
return {
firstMethod: function() { ... },
secondMethod: function() { ... },
thirdMethod: function() { ... }
}
})
and in the controller/directive
.controller('myCtrl', function(myService) {
myService.firstMethod();
myService.secondMethod();
myService.thirdMethod();
})

Categories