又一个异步服务 returns 未定义

Yet Another Asynchronous service returns Undefined

这是我的服务:

(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

我该如何解决?

这是因为,http请求还没有完成。只有在 http 请求完成后,您才会有数据。您可以尝试以下代码。还有 return 来自服务的 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,
    };
}

})();

您需要进行少量重构才能使其正常工作。

(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);
            });
        }
    });
})();