将 Angular HTTP.get 函数转换为服务 [英] Convert Angular HTTP.get function to a service

查看:27
本文介绍了将 Angular HTTP.get 函数转换为服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将 controllers.js 中的 Angular HTTP.get 函数转换为 services.js 中的服务.

I'm trying to convert an Angular HTTP.get function in my controllers.js to a service in services.js.

我发现的所有示例都有相互冲突的服务实现方式,而且它们的名称选择令人困惑.此外,服务的实际角度文档使用了与所有示例不同的语法.我知道这非常简单,但请在这里帮助我.

The examples I have found all have conflicting ways to implement the service and their choice of names is confusing. Furthermore, the actual angular documentation for services uses yet a different syntax than all the examples. I know this is super simple, but please help me out here.

我有 app.jscontrollers.jsservices.jsfilters.js.

app.js

angular.module('MyApp', []).
    config(['$routeProvider', function($routeProvider)
        {
            $routeProvider.
                when('/bookslist', {templateUrl: 'partials/bookslist.html', controller:             BooksListCtrl}).
                otherwise({redirectTo: '/bookslist'});
        }
    ]);

controllers.js

function BooksListCtrl($scope,$http) {
    $http.get('books.php?action=query').success(function(data) {
        $scope.books = data;
    });

    $scope.orderProp = 'author';
}

推荐答案

从模块和依赖注入的角度考虑.

Think in terms of modules and dependency injection.

所以,假设你有这三个文件

So, lets say you have these three files

<script src="controllers.js"></script>
<script src="services.js"></script>
<script src="app.js"></script>

你需要三个模块

angular.module('MyApp', ['controllers', 'services'])
  .config(['$routeProvider', function($routeProvider){
    $routeProvider
      .when('/bookslist', {
        templateUrl: 'partials/bookslist.html', 
        controller:  "BooksListCtrl"
      })
      .otherwise({redirectTo: '/bookslist'});
  }]);

注意,另外两个模块被注入到主模块中,所以它们的组件对整个应用程序都是可用的.

Notice that the other two modules are injected into the main module, so their components are available to the whole app.

目前您的控制器是一个全局函数,您可能希望将其添加到控制器模块中

Currently your controller is a global function, you might want to add it into a controllers module

angular.module('controllers',[])
  .controller('BooksListCtrl', ['$scope', 'Books', function($scope, Books){
    Books.get(function(data){
      $scope.books = data;
    });

    $scope.orderProp = 'author';
  }]);

Books 被传递给控制器​​函数,并由注入到 ma​​in 应用程序模块中的服务模块提供.

Books is passed to the controller function and is made available by the services module which was injected in the main app module.

这是您定义 Books 服务的地方.

This is where you define your Books service.

angular.module('services', [])
  .factory('Books', ['$http', function($http){
    return{
      get: function(callback){
          $http.get('books.json').success(function(data) {
          // prepare data here
          callback(data);
        });
      }
    };
  }]);

有多种注册服务的方式.

There are multiple ways of registering services.

  • service:传递一个构造函数(我们可以称之为类)并返回该类的一个实例.
  • provider:最灵活和可配置的,因为它允许您在实例化服务时访问注入器调用的函数
  • 工厂:传入一个注入器在实例化服务时调用的函数.
  • service: is passed a constructor function (we can call it a class) and returns an instance of the class.
  • provider: the most flexible and configurable since it gives you access to functions the injector calls when instantiating the service
  • factory: is passed a function the injector invokes when instantiating the service.

我更喜欢使用 factory 函数并让它返回一个对象.在上面的例子中,我们只返回一个带有 get 函数的对象,该函数传递了一个成功回调.您也可以更改它以传递错误函数.

My preference in using the factory function and just have it return an object. In the example above we just return an object with a get function that is passed a success callback. You could change it to pass an error function too.

编辑 在评论中回答@yair 的请求,以下是将服务注入指令的方法.

Edit Answering @yair's request in the comments, here's how you would inject a service into a directive.

我按照通常的模式,先添加js文件

I follow the usual pattern, first add the js file

<script src="directives.js"></script>

然后定义一个新模块并注册一些东西,在这种情况下是一个指令

Then define a new module and register stuff, in this case a directive

angular.module('directives',[])
  .directive('dir', ['Books', function(Books){
    return{
      restrict: 'E',
      template: "dir directive, service: {{name}}",
      link:function(scope, element, attrs){
        scope.name = Books.name;
      }
    };
  }]);

指令模块注入app.js中的主模块.

angular.module('MyApp', ['controllers', 'services', 'directives']) 

您可能希望遵循不同的策略并将模块注入指令模块

You might want to follow a different strategy and inject a module into the directives module

请注意,语法内联依赖注释对于几乎所有内容都是相同的.该指令注入了相同的 Books 服务.

Notice that the syntax inline dependency annotation is the same for almost everything. The directive is injected the same Books service.

更新的 Plunker:http://plnkr.co/edit/mveUM6YJNKIQTbIpJHco?p=preview

这篇关于将 Angular HTTP.get 函数转换为服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆