我的 service.js 中有此代码
function myService($http, $log) {
var API = 'https://myapi.net/api/api.php?';
$log.debug(API);
return {
getApi: function(inputValue, inputValue2) {
return $http({
url:API + inputValue + '=' + inputValue2,
method:'GET'
})
}
};
}
在我的 Controller 中:
vm.searchNetflix = function() {
netflixService.getApi(vm.searchResult, vm.searchResult2).then(function(result){
vm.ResultSearch = result.data;
$log.log('result' + result);
});
};
这2个值“SearchResult和SearchResults”我在输入中调用,并更改api url,
示例: https://myapi.net/api/api.php?mySearchResult=mySearchResult2
当我输入一个值时,它会返回正确的内容, 如果我输入无效的内容,则返回 404,如果某个值为空,则返回 400。
我如何才能验证此状态并返回到我的 View 中?
谢谢:)
最佳答案
将信息转发回您的 View 很大程度上取决于您的 View 的构造方式,但原则是确保您正确捕获错误条件。
这类似于 an example on $http
在文档中;您需要为您的 promise 提供另一种方法来覆盖错误条件。
vm.searchNetflix = function() {
netflixService.getApi(vm.searchResult, vm.searchResult2)
.then(function(result) {
vm.ResultSearch = result.data;
$log.log('result' + result);
}, function(errorResult) {
// extract information from the errorResult here
});
};
理想情况下,确定状态错误的原因所需的任何信息都应在 errorResult
对象中提供。
关于javascript - 如果 AngularJS 中的 Api 服务状态 == 404,则记录消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35964144/