另一项异步服务返回未定义的服务



这是我的服务:

(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

我该如何修复?

您需要次要重构才能工作。

(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,
        };
    }
})();
(function () {
    'use strict';
    var module = angular.module('app');
    module.component("client", {
        templateUrl: "app/client/client.html",
        controllerAs: "model",
        controller: function (ClientsService) {
            var model = this;
            //getClients() now returns a promise that is resolved
            //when the client list is loaded
            ClientsService.getClients().then(function(clients){
              model.clients = clients;
              console.log(model.clients);
            });
        }
    });
})();

这是因为,HTTP请求尚未完成。您只有在完成HTTP请求后才有数据。您可以尝试以下代码。也从服务中返回HTTP承诺。

 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,
    };
}

})();

最新更新