无法从angular服务向控制器返回列表数据

Unable to return list data from angular service to controller

本文关键字:控制器 返回 列表 数据 服务 angular      更新时间:2023-09-26

我试图从调用REST端点的angular服务返回一些数据,但是我似乎无法获得数据流,因为它是异步的。

我的服务方法。

   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: "" };
    }
}

问题是填充supportFiles的调用是异步的,所以当originalSupportFiles试图复制值时,supportFiles是未定义的。但也当我然后点击addApplicationFile()它不能推到值$范围。因为它认为它是未定义的,所以看起来值根本没有被加载,即使服务被调用并返回数据。

我做错了什么?

你需要返回一个承诺,然后从那里开始——这里有一种方法:

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

然后在控制器中:

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