Using AngularJs how to write code for Sucess and Failure - angularjs

How to apply Success And Failed in AngularCtrl
$scope.Btncall = function () {
var xx = MyService.GetDatafromApi();
xx.then(function (d) {
$scope.Employee = d.data;
}
),success(function (success) {
alert('ok');
})

What i understood is that you're asking how to handle a promise return success/fail like the one you get from the $http request service, so here's below an example:
$http.get('http://freegeoip.net/json')
.success(function (data, status, headers, config) {
//TODO When request Success
console.log(data);
$scope.Employee = data;
})
.error(function (data, status, headers, config) {
//TODO When request Failed
console.log(data); //Server Response values if there's any
$scope.Employee = [];
});

This is a sample code which helps you.
$scope.Btncall = function () {
MyService.GetDatafromApi().success(function (data, status,headers)
{
$scope.Employee = data;
})
.error(function (data, status, headers) {
$scope.Employee = [];
});
}
//Call Btncall Function..
$scope.Btncall();

Related

angular ionic $http service not working

Loading json using $http isn't working. Can't figure out where the problem is
.factory('streamStore', function ($http) {
var cachedData = null;
return {
findAll: function getAll() {
$http.get('img/sample.json').
success(function (data, status, headers, config) {
console.log("inside stream controller");
cachedData = data; return cachedData;
}).
error(function (data, status, headers, config) {
// log error
});
}
And in my controller this is how I'm calling it:
.controller('streamCtrl', function ($scope, ,streamStore) {
$scope.streams = streamStore.findAll();//not working ,
There is a error in your code . Check below
.factory('streamStore', function ($http) {
var cachedData = null;
return {
findAll: function() {
$http.get('img/sample.json').
success(function (data, status, headers, config) {
console.log("inside stream controller");
cachedData = data;
return cachedData;
}).
error(function (data, status, headers, config) {
// log error
});
}
and then call , as you were calling in your controller.
or use this
.factory('streamStore', function ($http) {
var cachedData = function(){
return $http.get('img/sample.json');
};
return {
findAll: function(){
return cachedData();
}
}
});
then in controller
streamStore.findAll().then(function(response){
console.log(response) // here is your data
})
since you have not returned anything from factory.
.factory('streamStore', function ($http) {
var cachedData = null;
return {
findAll: function getAll() {
$http.get('img/sample.json').
success(function (data, status, headers, config) {
console.log("inside stream controller");
cachedData = data; return cachedData;
// should return something
return cachedData
}).
error(function (data, status, headers, config) {
// log error
});
}
one more suggestion return promise to make it safe .
return $http.get('img/sample.json')...
and handle with then in controller.
.controller('streamCtrl', function ($scope, ,streamStore) {
streamStore.findAll().then(function(res){
//res will contain your data
$scope.streams = res.data;
});

multiple $http.get not working

Having issues bringing in multiple data from API endpoints.
Results come back undefined for values in $q.all method
$http.get('url').success(function(data, status, headers, config) {
$scope.data1= data;
})
$http.get('url').success(function(data, status, headers, config) {
$scope.data2= data;
})
$http.get('url').success(function(data, status, headers, config) {
$scope.data3= data;
})
$http.get('url').success(function(data, status, headers, config) {
$scope.data4= data;
})
$q.all([$scope.data1, $scope.data2, $scope.data3, $scope.data4]).then(function(values) {
$scope.data= values;
});
$q.all takes an array of promises so you'd have to do something like this.
$scope.promise1 = $http.get('url');
$scope.promise2 = $http.get('url');
$scope.promise3 = $http.get('url');
$scope.promise4 = $http.get('url');
$q.all([$scope.promise1, $scope.promise2, $scope.promise3, $scope.promise4]).then(function (values) {
$scope.data = values;
});

deferred.resolve giving error TypeError: undefined is not a function

I am using angularjs and cordova tool for creating application.
I have created service, which contains code for calling APIs. and in that I want to return response to my angular controller.
My code is,
Service,
JodoModule.factory('commonServices', function ($http, $q, $rootScope) {
return {
getServiceData: function (url) {
$rootScope.loading = true;
var deferred = $q.defer();
var req = {
method: 'GET',
url: url
}
$http(req).success(function (data) {
alert("data in service = " + JSON.stringify(data.Data));
deferred.resolve(data);
}).error(function (data, status, headers, config) {
deferred.reject(status);
});
return deferred.promise;
}
};
});
My controller is,
commonServices.getServiceData("My url").
success(function (data, status, headers, config) {
alert(data);
}).
error(function (data, status, headers, config) {
alert("Got error");
});
In above code, in service, its showing elert message for JSON.stringify(data.Data)); in success block, so data is comming, but its not executing deferred.resolve(data); properly...
in Web tool bar its giving me error,
ie. TypeError: undefined is not a function
My o/p is :
{"status":"SUCCESS","Message":"success","Token":"","Data":[{"Id":17,"UserId":"477f1919-6b80-4804-a325-ac0cb05bcd3e","UserName":"honey","FirstName":"honey","LastName":null,"ProfilePic":false,"Status":2}]}
How can I solve this error. ?
Ordinary $q promises don't have a .success() or .error() method, but you shouldn't be using the deferred antipattern anyway. Instead, do this:
JodoModule.factory('commonServices', function ($http, $rootScope) {
return {
getServiceData: function (url) {
$rootScope.loading = true;
var req = {
method: 'GET',
url: url
};
return $http(req).then(function (result) {
alert("data in service = " + JSON.stringify(result.data.Data));
return result.data;
});
}
};
});
Controller:
commonServices.getServiceData("My url").
then(function (data) {
alert(data);
}).
catch(function (result) {
alert("Got error");
});
Quite a bit cleaner, ay?

get the value of $scope.data in a variable in same controlled

My code is some thing
$scope.data = {};
var init = function () {
$http.post('views/Report.aspx/GetMailReport', {})
.success(function (data, status, headers, config) {
$scope.data = JSON.parse(data.d);
})
.error(function (data, status, headers, config) {
$scope.data = status;
})
};
init();
var data = $scope.data;
But the var data is returning empty {}
If you want a copy you should do as below... As the http call is asynchronous you assign inside the success callback method
$scope.data = {};
var data;
var init = function () {
$http.post('views/Report.aspx/GetMailReport', {}) .success(function (data, status, headers, config) {
$scope.data = JSON.parse(data.d);
data = $scope.data;
}) .error(function (data, status, headers, config) {
$scope.data = status;
}) };
init();
Edited:
Here is the link to a fiddle that I have created.

How can I make a function call depend on completion of two $http calls in AngularJS?

In my controller I have the following calls:
optionService.init($scope);
optionService.getSubjects1($scope);
optionService.getSubjects2($scope);
optionService.getAbc($scope);
Here's the code for the optionService:
angular.module('common')
.factory('optionService',
['$http',function ($http) {
var factory = {
init: function ($scope) {
$scope.option = {};
},
getSubjects1: function ($scope) {
var url = '/api/Subject1/GetSelect';
$scope.loading++;
$http.get(url)
.success(function (data, status, headers, config) {
$scope.option.subjects1 = data;
$scope.loading--;
})
.error(function (data, status, headers, config) {
$scope.loading--;
alert("Error: No data returned from " + url);
});
},
getSubjects2: function ($scope) {
var url = '/api/Subject2/GetSelect';
$scope.loading++;
$http.get(url)
.success(function (data, status, headers, config) {
$scope.option.subjects2 = data;
$scope.loading--;
})
.error(function (data, status, headers, config) {
$scope.loading--;
alert("Error: No data returned from " + url);
});
},
}
return factory;
}]);
Is there a way that I could make the call to optionService.getAbc depend on the completion of both the getSubjects1 and getSubjects2 calls? I will also soon be using Angular 1.2 if this makes any difference.
$q.all(promises) lets you combine multiple promises in to one:
optionService.getAbc = function($scope) {
$q.all([
optionService.getSubjects1($scope),
optionService.getSubjects2($scope)
])
.then(function() {
//...
});
}
Edit. Yes, you need to return promises from your getSubjects functions. To keep code changes to bare minimum, you could do something like this:
optionService.getSubjects1($scope) {
var url = '/api/Subject1/GetSelect';
$scope.loading++;
return $http.get(url)
.then(function (data, status, headers, config) {
$scope.option.subjects1 = data;
$scope.loading--;
}, function (data, status, headers, config) {
$scope.loading--;
alert("Error: No data returned from " + url);
});
}
With $http.then() you create a new promise that can be combined with other promises in getAbc()
You should rewrite your getSubject1 and getSubject2 to return promise. Also passing the $scope to the method and updating the scope from the service method is not a good way of doing things. You service methods should return data which assignable in your code. This makes your services more usable and readable.
If you change getSubject1 and getSubject2 in lines of
getSubjects1: function () {
var url = '/api/Subject1/GetSelect';
return $http.get(url);
}
In your controller you can do
$q.all([
optionService.getSubjects1(),
optionService.getSubjects2()
])
.then(function([data1, data2]) {
//use data1 to update scope for subject1
// use data2 to update scope for subject2
//call any service method.
});

Resources