如何获取$http.get()的url's值以在函数中使用

How to get the url's value of $http.get() to use inside the function?

本文关键字:函数 url 获取 何获取 http get      更新时间:2023-09-26

嗨,我用AngularJS解析了三个不同的web服务:

app.factory('myapp', ['$http', function($http) {        
function getLists() {
var tab = ['url1', 'url2', 'url3'];
var list = [];
for(i = 0; i < tab.length; i++) {
    $http.get(tab[i]) 
    .then(function(res) {
        res.data.error='';
        list.push(res.data);
    }).catch(function (res) {
res.data.error='file not found';
});
}
return list;
}
return {
getLists: getLists
};
]);

在一个html页面,我必须显示在Json文件中发现的数据<tr ng-repeat="d in list" ng-show="d.error == ''"> <td>{{d.nm}}</td> <td>{{d.cty}}</td>
<td>{{d.hse}}</td> <td>{{d.yrs}}</td> </tr> <tr ng-repeat="d in list"ng-show="d.error != ''"> <td>File not found</td></tr>

所以,如果没有找到URL或有一个错误,我应该显示一行,我把错误。我现在想要的是tp指定未找到的Url。例如,如果找不到url1,我想放一条消息url1+" is not found"我试着在我的工厂做这件事

res.data.error= tab[i]+' file not found';

和在我的HTML中:

<tr ng-repeat="d in list"ng-show="d.error != ''">
  <td>{{d.error}}</td></tr>

但是什么都没有出现,当我使用警告来调试

alert(tab[i]+' file not found');

我得到'未定义的文件未找到'。有办法解决我的问题吗?

使用响应对象,res.config.url包含被击中的url。但是,由于url不存在,将执行.catch block而不是.then block

$http.get(tab[i]) 
.catch(function(res) {
   res.data = { error : res.config.url +' file not found' };
})

同样,您将不得不使调用代码异步使用它,现在您正在尝试以同步方式访问,这将永远不会工作…