Angular 服务(Services)

本文介绍了AngularJS服务的使用场景、定义方法,包括factory、service和provide,并对比了三者的区别。通过示例详细阐述如何创建自定义服务,并强调了provider方法在全局配置中的独特作用。
部署运行你感兴趣的模型镜像

为什么要使用服务

当需要向各种模块提供通用功能时使用服务。

例如,我们可能具有可以在各个模块之间重用的数据库功能。因此,您可以创建一个具有数据库功能的服务。

什么是服务

AngularJS 中的服务是一个函数或对象。

AngularJS 中你可以创建自己的服务,或使用内建服务

注意:与其他核心AngularJS标识符一样,内置服务始终以$ (例如$http)开头。

使用服务

<div ng-app='myApp' ng-controller='getUrlCtrl'>
        <h3>{{myUrl}}</h3>
    </div>
    <script>
        var app = angular.module('myApp', [])
        app.controller('getUrlCtrl', [
            '$scope',
            '$location',
            function ($scope, $location) {
                $scope.myUrl = $location.absUrl();
            }
        ])
    </script>

上面的实例,使用了$location服务获取当前页面的url

创建自己的Services

在AngularJS中,内置的服务都是以$开头,所以我们的自定义服务尽量避免以$开头。自定义服务的方式有如下几种:

  • 使用Module的provider方法
  • 使用Module的factory方法
  • 使用Module的service方法

使用factory方法

通过factory方法创建的服务必须有返回值,即必须有return函数,它可以返回任意类型的值,包括基本数据类型或者对象类型。
如果没有return函数,则会报错。

factory注入的结果就是return返回的结果,可以在被注入的对象中使用注入的结果定义的各种方法.
定义

  app.factory('UtilFactoryService', function () {
            var factory = {};
            factory.getTestString = function () {
                return 'Hello Services'
            }
            return factory
        })

调用,需要注入定义的services 名字UtilFactoryService

        var app = angular.module('myApp', [])
        app.controller('getUrlCtrl', [
            '$scope',
            'UtilFactoryService',
            function ($scope, UtilFactoryService) {
                $scope.hello = UtilFactoryService.getTestString();
            }
        ])

使用service方法

1、有返回值写法,与factory方法相似

app.service('TestService', function () {
            var TestService = {};
            TestService.getTestString = function () {
                return 'Hello Services'
            }
            return TestService
        })

2、无返回值写法,需要加this 调用

 app.service('TestService', function () {
            this.getTestString = function () {
                return 'Hello Services'
            }
        })

使用provide方法

 app.provider('myProvider', function () {
            this.artist = '';
            this.thingFromConfig = '';

            this.$get = function () {
                var that = this;
                return {
                    getArtist: function () {
                        return that.artist;
                    },
                    getThingFromConfig: function () {
                        return that.thingFromConfig;
                    }
                }
            };
        });

        app.config(function (myProviderProvider) {
            myProviderProvider.thingFromConfig = 'hello service';
        });

使用provide方法创建服务有以下几个注意点

  • 必须使用$get方法,provide注入的结果就是get方法返回的结果,如果不包含$get方法,则程序会报错。
  • 在三种创建服务的方法中,只有使用provider方法创建的服务才可以传进config函数,以用于在对象启用之前,对模块进行配置。但是在config中进行配置的只能是在$get函数之外定义的变量,在下面定义的provider中只有artist与thingFromConfig两个变量可以被访问到,而getArtist与getThingFromConfig两个方法是不能被在config函数中访问到的。
  • 而且在注入config函数中时,参数名必须由服务名+Provider组成,例如下面的例子注入到config函数中的就是myProviderProvider

三种方法的比较

  • 需要在config中进行全局配置的话,只能选择provider方法
  • factory和service是使用比较频繁的创建服务的方法。他们之间的唯一区别是:service方法用于注入的结果通常是new出来的对象,factory方法注入的结果通常是一系列的functions
  • provider是创建服务最为复杂的方法,除非你需要创建一个可以复用的代码段并且需要进行全局配置,才需要使用provider创建
  • 所有具有特定性目的的对象都是通过factory方法去创建

您可能感兴趣的与本文相关的镜像

Qwen-Image

Qwen-Image

图片生成
Qwen

Qwen-Image是阿里云通义千问团队于2025年8月发布的亿参数图像生成基础模型,其最大亮点是强大的复杂文本渲染和精确图像编辑能力,能够生成包含多行、段落级中英文文本的高保真图像

Angular 2 Services by Sohail Salehi English | 6 Apr. 2017 | ISBN: 1785882619 | 311 Pages | EPUB/PDF (conv) | 12.39 MB Key Features Leverage the latest Angular 2 and ES2016 features to create services Integrate third-party libraries effectively and extend your app's functionalities Implement a real-world case study from scratch and level up your AngularJS skills Book Description A primary concern with modern day applications is that they need to be dynamic, and for that, data access from the server side, data authentication, and security are very important. Angular 2 leverages its services to create such state-of-the-art dynamic applications. This book will help you create and design customized services, integrate them to your applications, import third-party plugins, and make your apps perform better and faster. This book starts with a basic rundown on how you can create your own Angular 2 development environment. You will then use Bootstrap and Angular UI components to create pages. You will also understand how to use controllers to collect data and populate them into NG UIs. Later, you will then create a rating service to evaluate entries and assign a score to them. Next, you will create "cron jobs" in NG. We will then create a crawler service to find all relevant resources regarding a selected headline and generate reports on it. Finally, you will create a service to manage accuracy and provide feedback about troubled areas in the app created. What you will learn Sketch and create wire-frames for your project Use controllers to collect data and populate them into NG UIs Create a controller and the required directives to build a tree data structure Implement a logic to decide the relevancy of any given evidence Create a partially-AI service Build controllers to set the template for the report Collect, investigate, perform decision-making, and generate report in one big automated process
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值