Angularjs没有加载json文件

Angularjs not loading json files

本文关键字:json 文件 加载 Angularjs      更新时间:2023-09-26

我不知道为什么当我在一个html页面上打印json文件的工作,也从一个按钮调用一个函数,但不是在javascript文件。

这是一个问题,因为我需要排序json文件中的数据之前显示它从网页,我不能使它工作。我尝试使用这个解决方案https://stackoverflow.com/a/15463124/2796268,但是控制台说

jsonDat未定义

我代码:

$scope.init = function () {
        console.log("init");
    $http.get('json/file.json') .success(function(data) {
           $scope.jsonDat = res.data; 
        })
        .error(function(data,status,error,config){
            $scope.jsonDat = [{heading:"Error",description:"Could not load json   data"}];
        });
     console.log(jsonDat);
};

如何处理json数据之前的页面加载或当页面加载?

您可以在从$http返回数据时处理数据,如下所示:

$scope.init = function () {
    $http.get('json/file.json').success(function(data) {
        //---- SORT HERE ----
        $scope.jsonDat =  mySortFunction(data);
    });
};

试试这个:

$scope.init = function() {
    console.log("init");
    $http.get('json/file.json').success(function(data) {
            $scope.jsonDat = data;
            console.log($scope.jsonDat);
        })
        .error(function(data, status, error, config) {
            $scope.jsonDat = [{
                heading: "Error",
                description: "Could not load json   data"
            }];
            console.log($scope.jsonDat);
        });
};

在成功中,你有数据,但你试图从res.data中获取。当你使用success时,它不是对数据的响应,而是对数据的响应。

我以为你想排序一些JSON文件,然后显示在HTML页面。所以我的想法是得到JSON文件(你试过)

$http.get('json/file.json') .success(function(data) {
       $scope.jsonDat = data.res; 
       console.log('Checking the result',angular.toJson($scope.jsonDat));
    })

但是把结果放在

$scope.jsonDat = data.res; 

,

sortService.sortJsn = data.res;

美元范围。jsonDat而不是创建angular service把你的数据倒在那里,然后你可以在你的控制器排序的任何地方访问这些数据,它也显示在HTML中。