Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angularjs/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
AngularJS更改动态$http.get_Angularjs_Json_Http - Fatal编程技术网

AngularJS更改动态$http.get

AngularJS更改动态$http.get,angularjs,json,http,Angularjs,Json,Http,我最近学习了AngularJS。我开始了一个小项目。我能够从json文件中提取数据。我当前的任务是能够从多个json文件中提取数据。我该怎么做 我以这种方式创建了我的第一个json文件: $http.get("personel.json") .then(function(gelen) { $scope.personeller = gelen.data; }); 我还需要获取9个json文件,但我想查看我调用的文件的

我最近学习了AngularJS。我开始了一个小项目。我能够从json文件中提取数据。我当前的任务是能够从多个json文件中提取数据。我该怎么做

我以这种方式创建了我的第一个json文件:

$http.get("personel.json")
            .then(function(gelen) {
                $scope.personeller = gelen.data;
            });
我还需要获取9个json文件,但我想查看我调用的文件的数据

$http.get("1.json")
            .then(function(veri1) {
                $scope.x1 = veri1.data;
            });
其他文件名为“1.json、2.json、3.json…….9.json”



如何更改1.json在顶部代码块中的位置?对不起,我的英语不好。这是我第一次给外国论坛写信。提前感谢

您可以将$http调用包装在一个函数中,并按如下方式传入要检索的文件名:

Edit我修改了这里的代码,添加了一个承诺,以处理异步请求可能产生的问题

$scope.getFile = async function(fileName){
    return new Promise((res, err) => {
        $http.get(fileName).then(function(result){
             res(result.data);
        })
    })
}

$scope.file1 = $scope.getFile("1.json");
$scope.file2 = $scope.getFile("2.json");
$scope.file3 = $scope.getFile("3.json");
$scope.file4 = $scope.getFile("4.json");
$scope.file5 = $scope.getFile("5.json");
$scope.file6 = $scope.getFile("6.json");
$scope.file7 = $scope.getFile("7.json");
$scope.file8 = $scope.getFile("8.json");
$scope.file9 = $scope.getFile("9.json");
如果文件是连续的和数字的,您也可以使用它使用for循环将文件中的所有数据拉入单个数组

$scope.returnedFiles = [];
for(i = 0; i < 9; i++){
    $scope.getFile(i + ".json").then(fileData => {
        $scope.returnedFiles.push(fileData);
    });

}
$scope.returnedFiles=[];
对于(i=0;i<9;i++){
$scope.getFile(i+“.json”)。然后(fileData=>{
$scope.returnedFiles.push(fileData);
});
}

我用这种方法解决了我的问题,谢谢。
$http.get
是一个异步调用,当您编写
$scope.returnedFiles.push(文件)时您可以推送空/空对象。您的代码可能无法运行。感谢@carmelolg的反馈,我修改了我的代码以解决此问题。不客气,现在您只需管理以前返回的承诺即可。通过
async
返回的ES6承诺未与AngularJS执行上下文集成。只有在AngularJS执行上下文中应用的操作才会受益于AngularJS数据绑定、异常处理、属性监视等。$http服务已经返回AngularJS承诺。无需生产带有
新承诺的新产品
。如果$http服务返回被拒绝的承诺,则生成的承诺将挂起。
$scope.getdetail = function(detail) {
    $scope.result = detail;

    $http.get($scope.result.id + ".json")
        .then(function(veri1) {
            $scope.x1 = veri1.data;
        });
}