I am trying to call a endpoint using $http.get and check if the succsess code is 200 then use the response data otherwise I need to call other endpoint. I tried to check if the call is success or error like below,
$scope.getRequest = function () {
var url = $rootScope.BaseURL;
var config = {
headers: {
'Authorization': `Basic ${$scope.key}`,
'Prefer': 'odata.maxpagesize=10000'
}
};
$http.get(url, config)
.success(
function (response) { // success async
$scope.viewRequest.data = response.data;
})
.error(function (response) { // failure async
var url = $rootScope.diffURL;
$http.get(url, config)
.success(
function (response) { // success async
$scope.viewRequest.data = response.data;
})
.error(function (response) { // failure async
console.log("There was an error getting the request from CORE");
});
});
};
I was hoping if the call to $scope.BaseURL
fails it will go to the error function and calls the $scope.diffURL
returns the response but I am getting below errors
angular.js:14800 TypeError: $http.get(...).success is not a function
GET https:\\example.com\... 400 (Bad Request)
Possibly unhandled rejection:
{"data":{"error":{"code":"1001","message":"
The property, used in a query expression, is not defined in type 'T'."}},"status":400,"config":{"method":"GET","transformRequest":[null],"transformResponse":[null],"jsonpCallbackParam":"callback","headers":{"Authorization":"Basic 0h","Prefer":"odata.maxpagesize=10000","Accept":"application/json, text/plain, /"},"url":"https://example.com...,"statusText":"Bad Request","xhrStatus":"complete"}`
To achieve expected use below option of chaining API calls with $http.get with then instead of success ,as it is used to Angularjs version 1.3 and from above 1.3 use .then()
$http.get('<url>') // Replace url, url2 with actual urls
.then(function(response){
}, function(error){
$http.get('<url2>')
.then(function(response2){
// Handle response
}, function(error2){
}
})
working code sample for reference
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
$scope.main= '';
$http.get("https://output.jsbin.com/http-promise-chain-json/14.json") //Invalid URL
.then(function(response) {
console.log("success first call")
$scope.main= response.data;
}, function(error){
console.log("error")
$http.get("https://output.jsbin.com/http-promise-chain-json/1.json")
.then(function(response) {
$scope.myWelcome = response.data;
}, function(error) {
})
});
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<h1>{{myWelcome}}</h1>
<h1>{{main}}</h1>
</div>
<script>
</script>
</body>
codepen - https://codepen.io/nagasai/pen/jgOgmV