另一个异步服务返回Undefined

时间:2016-12-26 15:18:54

标签: angularjs angular-promise angular-services angular-http

这是我的服务:

(function () {
    'use strict';

    angular
        .module('app')
        .service('ClientsService', Service);

    function Service($http) {

        function getClients() {
            $http.get('app/client/clients.json')
                .then(function(res){
                    return res.data;
                });
        }

        return {
            getClients: getClients,
        };
    }
})();

如果我在then内的控制台日志,我可以从json文件中获取客户端。 然后我想在我的组件中使用该服务:

(function () {
    'use strict';

    var module = angular.module('app');

    module.component("client", {
        templateUrl: "app/client/client.html",
        controllerAs: "model",
        controller: function (ClientsService) {
            var model = this;
            model.clients = ClientsService.getClients();
            console.log(model.clients)
        }
    });
})();

但是日志告诉我:undefined

我该如何解决?

2 个答案:

答案 0 :(得分:1)

这是因为,http请求尚未完成。只有在完成http请求后才能获得数据。您可以尝试以下代码。同时从服务中返回http promise。

 module.component("client", {
    templateUrl: "app/client/client.html",
    controllerAs: "model",
    controller: function (ClientsService) {
        var model = this;
        ClientsService.getClients().then(function(clients){
            model.clients = clients;
            console.log(model.clients)
        })
    }
});

像这样改变服务:

(function () {
'use strict';

angular
    .module('app')
    .service('ClientsService', Service);

function Service($http) {

    function getClients() {
         return $http.get('app/client/clients.json')
            .then(function(res){
                return res.data;
            });
    }

    return {
        getClients: getClients,
    };
}

})();

答案 1 :(得分:1)

您需要进行微调才能实现此目的。

environments:

    development:

        dataSources:

            dataSource:

                dbCreate: create-drop
(function () {
    'use strict';

    angular
        .module('app')
        .service('ClientsService', Service);

    function Service($http) {

        function getClients() {
            //Notice the return here? we're returning a promise.
            return $http.get('app/client/clients.json')
                .then(function(res){
                    return res.data;
                });
        }

        return {
            getClients: getClients,
        };
    }
})();