javascript - $http.get 处理两个不同的调用
问题描述
我正在尝试使用 $http.get 调用端点并检查成功代码是否为 200,然后使用响应数据,否则我需要调用其他端点。我试图检查调用是成功还是错误,如下所示,
$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");
});
});
};
我希望如果调用$scope.BaseURL
失败,它将转到错误函数并调用$scope.diffURL
返回响应,但我得到以下错误
angular.js:14800 TypeError: $http.get(...).success 不是函数
GET https:\\example.com\... 400 (Bad Request)
可能未处理的拒绝:
{"data":{"error":{"code":"1001","message":"
在查询表达式中使用的属性未在类型 '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"}`
解决方案
为了实现下面的预期使用,使用 $http.get 链接 API 调用的选项,然后而不是成功,因为它用于 Angularjs 版本 1.3 并且从 1.3 以上使用 .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){
}
})
工作代码示例供参考
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
推荐阅读
- sharepoint-2013 - Sharepoint 2013 PickerTreeView 更改字体颜色
- javascript - jQuery AJAX POST 对 PHP 的请求必须提交两次才能工作
- javascript - JavaScript 原型:冲突的结果
- sql-server - 计算日期差异,比较行并创建新的一次
- c# - Bot Framework Directline 发送通知 C#
- android - Parcelize 在对象和枚举上抱怨“Parcelable 应该是一个类”
- intellij-idea - 如何缩小 JetBrains IDE 工具窗口?
- scala - IntelliJ SBT 项目导入问题
- transactions - 应用程序异常的ejb事务回滚不起作用
- c# - 在过滤“内部”联接的文档时选择联接的“外部”文档?