javascript - 在 angularjs 中使用服务

标签 javascript angularjs benchmarking angular-services

我在网上读到,您应该使用服务来获取数据,而不是简单地将代码放在 Controller 中,以保持 Controller 精简。

这是我的 Controller ,它获取员工列表:

angular.module("app").controller("MyController", function ($scope, $http) {
    $http.get("/api/getempl").then(function (response) {
        if (response.status == 200) {
            $scope.empData = response.data.data;
        } else {
            console.log('400');
        }
    });
});

然后我尝试了 _Service 方法以希望提高性能

angular.module("app").factory("testService", function ($http, $location) {
    return {
        getData: function () {
            var promise = $http.get("/api/getempl").then(function (response) {
                return response.data.data;
            });
            return promise;
        }
    };
});

现在,当我像显示的那样注入(inject)服务,并在 net 选项卡下的 firebug 中对其进行测试时,页面加载时间没有改善,反而增加了。

我在代码中做错了什么,或者我在 AngularJS 中使用服务时缺少什么概念?

angular.module("app").controller("MyController", function ($scope, $http, testService) {
    testService.getData().then(function (response) {
        $scope.empData = response;
    });
});

最佳答案

建议使用服务不是为了性能,而是为了关注点分离和代码整洁。话虽如此,如果您的 Controller 只有一个 $http 调用,那么仅仅为了提供服务而创建服务是没有意义的。

关于javascript - 在 angularjs 中使用服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25741598/

相关文章:

javascript - Safari 浏览器上的属性下载

c# - 如何让 C# 与 Javascript 互操作?

apache - 使用数据库示例数据生成负载的工具

javascript - 下拉列表索引更改时日期选择器不起作用

javascript - arcgis javascript 如何关闭图层

javascript - 如何使用angularJS过滤选中的复选框

AngularJs : How to call child component method from parent components

angularjs - $httpBackend (angularJS) 中的 URL 参数

c++ - VS2005、VS2008下C++生成的EXE速度; VS2010编译器

r - 为什么 sapply 缩放比具有样本大小的 for 循环慢?