$resource 在 AngularJS 中响应一个空数组

$resource responses an empty array in AngularJS

我想显示一个 table,其中的项目来自 json 个数据。我已经为 return json 数据创建了一个服务。在我的 Ctrl 中,我正在查询服务以接收包含数据的数组。它有点困惑。因为我将响应放在一个新的 JS 变量中,然后将 JS 变量放在一个范围变量中。我在我的 html 文件中的 ngRepeat 指令中使用范围变量,然后它必须在 table 中显示数据,但它们不是那样。

服务:

myApp.factory('MyService', function ($resource) {
    return $resource('data/mydata.json');
});

Ctrl:

var MyData = MyService.query(function () {
        $log.info('[Result:]', MyData); //console shows the expected data
    });

$scope.datas = MyData;
$log.info('Result2:', $scope.datas); //console shows an empty array

查看:

<tr ng-repeat="item in filteredData = (datas | filter:search)>
    <td>{{ item.id }}</td>
    <td>{{ item.name }}</td>
</tr>

通常数据必须包含在变量 MyData 中,不是吗?

编辑: 新问题是,我的列表不会排序。我正在使用来自 angularjs 文档网站的 orderBy 过滤器。

你的

MyService.query....

async调用。 JS 不等待其响应并执行下一行

$scope.datas = MyData;

因此你得到空数组。

将您的代码更改为:

var MyData = MyService.query(function () {
    $log.info('[Result:]', MyData); //console shows the expected data
    $scope.datas = MyData;
    $log.info('Result2:', $scope.datas);
});