首页 > 解决方案 > 如何访问从同一控制器中服务块外部的 api 接收的数据

问题描述


我正在使用 Angular 1.7.8,并且我有一个控制器调用从 API 接收数据的服务,问题是,我无法访问同一控制器中服务块之外的数据。

app.controller('AppController', function ($scope, DataService) {

    let fieldProperties = {};

    $scope.findInData = function (value) {
        DataService.getData().then(function (response) {
            $scope.result = response.data;
            if (response.data !== undefined) {
                for (let idx in $scope.result) {
                    if ($scope.result.hasOwnProperty(idx)) {
                        if (value === $scope.result[idx].fieldname) {
                            fieldProperties = {
                                'fieldName': $scope.result[idx].fieldname,
                                'preferredFieldName': $scope.result[idx].preferredfieldname,
                                'fieldValue': $scope.result[idx].fieldvalue,
                                'isEditable': $scope.result[idx].editable,
                                'isMandatory': $scope.result[idx].mandatory,
                                'isAutoClear': $scope.result[idx].autoclear
                            };
                        }
                    }
                }
            }
        });
    };

    $scope.resultFieldProperties = fieldProperties;
});

另外我想提一下,直接将 $scope 放在 fieldProperties 上对我来说不是一个解决方案,因为我需要将此结果发送到指令范围,fieldProperties 对象因为范围在服务块之外也是未定义的,请提供其他建议!?

标签: javascriptangularjsrest

解决方案


您可以通过调用函数将结果返回给您的变量

$scope.findInData = function (value) {
    DataService.getData().then(function (response) {
        $scope.result = response.data;
        if (response.data !== undefined) {
            for (let idx in $scope.result) {
                if ($scope.result.hasOwnProperty(idx)) {
                    if (value === $scope.result[idx].fieldname) {
                        fieldProperties = {
                            'fieldName': $scope.result[idx].fieldname,
                            'preferredFieldName': $scope.result[idx].preferredfieldname,
                            'fieldValue': $scope.result[idx].fieldvalue,
                            'isEditable': $scope.result[idx].editable,
                            'isMandatory': $scope.result[idx].mandatory,
                            'isAutoClear': $scope.result[idx].autoclear
                        };
                        return fieldProperties;
                    }
                }
            }
        }
    });
};

$scope.resultFieldProperties = $scope.findInData('<some_value>');

否则,您需要有一个回调函数作为参数,并且可以在完成时向您返回数据。


推荐阅读