转换角度HTTP.get功能服务 [英] Convert Angular HTTP.get function to a service

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

问题描述

我想一个角在我的 controllers.js 转换 HTTP.get 函数将服务 services.js

我发现所有的例子有冲突的方式来实现服务和他们选择的名字是混乱的。此外,对于服务的实际角文档使用一个不同的语法比所有的例子。我知道这是超级简单,但请帮我在这里。

app.js controllers.js services.js filters.js

app.js

angular.module('MyApp的',[])。
    配置(['$ routeProvider',函数($ routeProvider)
        {
            $ routeProvider。
                当('/ bookslist',{templateUrl:'谐音/ bookslist.html',控制器:BooksListCtrl})。
                否则({redirectTo:'/ bookslist'});
        }
    ]);

controllers.js

函数BooksListCtrl($范围,$ HTTP){
    $ http.get('books.php?行动=查询')。成功(功能(数据){
        $ scope.books =数据;
    });    $ scope.orderProp ='作家';
}


解决方案

想想模块和依赖注入的条款。

所以,让我们说,你有这三个文件

<脚本SRC =controllers.js>< / SCRIPT>
&所述; SCRIPT SRC =services.js>&下; /脚本>
&所述; SCRIPT SRC =app.js>&下; /脚本>

您将需要三个模块

1。主要应用模块

angular.module('MyApp的',['控制器','服务'])
  的.config(['$ routeProvider',函数($ routeProvider){
    $ routeProvider
      。当('/ bookslist',{
        templateUrl:'谐音/ bookslist.html',
        控制器:BooksListCtrl
      })
      不然的话({redirectTo:'/ bookslist'});
  }]);

注意,其它两个模块被注入到主模块,所以它们的组件可用于整个应用程序

2。控制器模块

目前控制器是一个全球性的功能,你可能想将其添加到一个控制器模块

angular.module('控制器',[])
  .controller('BooksListCtrl',['$范围,图书,函数($范围,书籍){
    Books.get(功能(数据){
      $ scope.books =数据;
    });    $ scope.orderProp ='作家';
  }]);

图书传递给控制器​​的功能,并通过其在应用模块中注入的服务模块提供。

3。服务模块

这是你定义你的图书服务。

angular.module('服务',[])
  .factory('书',['$ HTTP',函数($ HTTP){
    返回{
      得到:函数(回调){
          $ http.get('books.json')。成功(功能(数据){
          //这里prepare数据
          回调(数据);
        });
      }
    };
  }]);

有注册服务的多种方式。


  • 服务:传递一个构造函数(我们可以称之为类),并返回类的一个实例。

  • 提供:最灵活和可配置的,因为它可以让你访问功能注射器调用实例化服务时

  • 工厂:传递函数实例化服务时,喷油器调用

在使用工厂功能,只是有它返回一个对象我的preference。在上面的例子中我们只是返回与传递成功回调 GET 函数的对象。你可以改变它传递一个错误的功能了。


修改回答@亚伊尔在评论的要求,这里是你将如何注入一个服务为一体的指令。

4。指令模块

我按照以往的模式,首先添加的js文件

<脚本SRC =directives.js>< / SCRIPT>

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

angular.module('指令',[])
  .directive('目录',['书',函数(书籍){
    返回{
      限制:'E',
      模板:DIR指令,服务:{{名}}。
      链接:功能(范围,元素,ATTRS){
        scope.name = Books.name;
      }
    };
  }]);

注入的指令模块到的主模块的在 app.js

angular.module('MyApp的',['控制器','服务','指令'])

您可能要遵循不同的策略和注入模块插入的指令模块

注意语法的内联依赖注释的是几乎所有的东西是一样的。该指令被注入相同的书籍的服务。

更新Plunker :<一href=\"http://plnkr.co/edit/mveUM6YJNKIQTbIpJHco?p=$p$pview\">http://plnkr.co/edit/mveUM6YJNKIQTbIpJHco?p=$p$pview

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.

I have app.js, controllers.js, services.js, filters.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>

You would need three modules

1. Main App Module

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.

2. Controllers Module

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 is passed to the controller function and is made available by the services module which was injected in the main app module.

3. Services Module

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: 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.

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.


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

4. Directives Module

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

Inject the directive module to the main module in app.js.

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

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

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

Updated Plunker: http://plnkr.co/edit/mveUM6YJNKIQTbIpJHco?p=preview

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

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