无法将角度服务中的列表数据返回到控制器

时间:2015-10-22 16:17:16

标签: javascript angularjs

我正在尝试从调用REST端点的角度服务返回一些数据,但是我似乎无法正确地获取数据流。

我的服务方式。

   appService.getApplicationSupportFiles = function () {
        $http.post("/SEFlex/SEFlexAdmin/GetApplicationSupportFiles")
            .then(function (response, status, headers, config) {
                if (response.data) {
                    var list = JSON.parse(response.data.data);
                    return list;
                }
            });
    }

我的控制器

function ShowApplicationFilesController($scope, $http, $modalInstance, $log, SEApplicationService, $rootScope, AlertsService) {

    $rootScope.closeAlert = AlertsService.closeAlert;
    $scope.supportFiles = [];
    $scope.originalSupportFiles = [];
    $scope.isBusy = false;

    $scope.newFile = {
        localFile: "",
        cloudFile: "",
    }

    // Load the initial files
    $scope.supportFiles = SEApplicationService.getApplicationSupportFiles();
    $scope.originalSupportFiles = $scope.supportFiles;

    $scope.addApplicationFile = function() {
        var file = { LocalPath: $scope.newFile.localFile, ShareName: "b", FolderName: "c", FileName: "d" };
        $scope.supportFiles.push(file);
        $scope.newFile = { localFile: "", cloudFile: "" };
    }
}

问题是对fillFiles的调用是异步的,所以当originalSupportFiles尝试复制值时,supportFiles是未定义的。但是当我再单击addApplicationFile()时,它无法推送到值$ scope.supportFiles,因为它认为它是未定义的,所以看起来这些值根本没有被加载,即使服务被调用并且返回数据。

我做错了什么?

1 个答案:

答案 0 :(得分:0)

你需要回复一个承诺并从那里开始 - 这是一种方式:

return $http.post("/SEFlex/SEFlexAdmin/GetApplicationSupportFiles").then(function (response, status, headers, config) {
    return response.data;
});

然后在你的控制器中:

SEApplicationService.getApplicationSupportFiles().then(function(list) {
    $scope.supportFiles = list;
});