为什么使用Angular Service来收集信息,而不仅仅是$ http?

Pau*_*000 3 javascript angularjs angularjs-service angularjs-http

两个选项,哪个更好,为什么:

例A.

  1. 应用模块
  2. 包含模型数据的服务
  3. 控制器从服务中调用数据

文件1 Users.js::

      angular.module('users', []);
Run Code Online (Sandbox Code Playgroud)

文件2 userService.js::

angular.module('users').service('userService', ['$q', UserService]);

  function UserService($q) {
    var users = [
      {
        name: 'Bob Smith',
        age: 26,
        address: 'London',
      },
      {
        name: 'John Simpson',
        age: 41,
        address: 'New York',
      },
      {
        name: 'Maria West',
        age: 36,
        address: 'Chicago',
      }
    ];

    // Promise-based API
    return {
      loadAllUsers : function() {
        // Simulate async nature of real remote calls
        return $q.when(users);
      }
    };
  }

})();
Run Code Online (Sandbox Code Playgroud)

文件3 UserController.js::

          angular.module('users').controller('UserController', ['$scope', function($scope) {

        $scope.selected     = null;
        $scope.users        = [];
        $scope.selectUser   = selectUser;
        $scope.toggleList   = toggleUsersList;
        $scope.makeContact  = makeContact;

        userService
          .loadAllUsers()
          .then( function( users ) {
            $scope.users    = [].concat(users);
            $scope.selected = users[0];
          });
}]);
Run Code Online (Sandbox Code Playgroud)

例B:

  1. app模块和控制器从.json文件到$ http服务绘制模型数据.
  2. 用于保存模型数据的json文件.

文件1 Users.js::

      angular.module('users', []);

         .controller('userController', [
            '$scope', 
            '$http', 
            function($scope, $http, $routeParams) {

            $http.get('data.json').success(function(data) {
            $scope.userData = data; 
            });

         }]);
Run Code Online (Sandbox Code Playgroud)

文件2: userService.json

         [
          {
            'name': 'Bob Smith',
            'age': 26,
            'address': 'London',
          },
          {
            'name': 'John Simpson',
            'age': 41,
            'address': 'New York',
          },
          {
            'name': 'Maria West',
            'age': 36,
            'address': 'Chicago',
          }
        ];
Run Code Online (Sandbox Code Playgroud)

B似乎更合乎逻辑(对我来说更容易),但我看到人们做A.我认为有一个优势 - 任何人都可以解释它吗?

Pan*_*kar 6

是的,A看起来是首选的方法,因为它看起来很像separation of concern,遵循单一责任原则.

服务

  • 哪个负责从后端获取数据
  • 向其他组件暴露各种方法以从单个位置检索数据.

调节器

  • 在服务和视图之间进行通信
  • 它还处理其他视图特定的业务逻辑.

为什么方法B不好?

你在控制器本身内有简单的ajax调用.雅看起来真的很棒.

但是假设你想要userData在另外两页上显示,那么你会做什么?我知道你也会在其他控制器中复制相同的代码.这里的问题出现在图片中.同样的事情将无缘无故地重复多次.正确?因此,在多个地方复制代码将Code Maintainability在未来增加问题.这就是原因,你不应该采取第一种方法.

在哪里采用方法A将具有更好的可维护和结构化代码.

编辑

在你的内心你approach A不应该硬编码所有的数据.它应该通过调用服务器API方法或调用.json文件从服务器检索.另外我要写下正确的服务代码approach A,你可以看到这个解释结束后.通过查看重构代码,您可以看到我们现在已经摆脱了$q服务.因为您不需要担心自定义承诺实现,因为$http方法确实返回promise,通过使用哪些代码可以遵循承诺链模式通过使用.then

angular.module('users').service('userService', ['$http', UserService]);
  function UserService($http) {
    return {
      loadAllUsers : function() {
        // Simulate async nature of real remote calls
        return $http.get('users.json'); //return promise from herer
      }
    };
  }
})();
Run Code Online (Sandbox Code Playgroud)