angularjs 实例_AngularJS服务示例教程

angularjs 实例

Today we will look at one of the important angular concepts called AngularJS Services. In the previous tutorial, we looked at AngularJS routing feature with a simple example.

今天,我们将介绍一个名为AngularJS Services的重要角度概念。 在上一教程中,我们通过一个简单的示例介绍了AngularJS路由功能。

AngularJS服务 (AngularJS Services)

Angular services are singleton objects that carry out some sort of task. We also use AngularJS services to organize and share code across the application.

Angular服务是执行某些任务的单例对象。 我们还使用AngularJS服务在整个应用程序中组织和共享代码。

Angular Services follow Single Responsibility Principle (SRP) and are wired together using dependency injection (DI). The Single Responsibility principle ensures that each object will have only a single responsibility.

Angular服务遵循单一职责原则(SRP),并使用依赖项注入(DI)连接在一起。 单一责任原则确保每个对象仅具有单一责任。

For Example, controllers are responsible for wiring model data to views. It will violate the Single Responsibility Principle, if we use controllers to carry out some other logic. Therefore, the business logic should be abstracted out into services and they are injected when needed. This makes the application more manageable and testable.

例如,控制器负责将模型数据连接到视图。 如果我们使用控制器执行其他逻辑,它将违反单一责任原则。 因此,应该将业务逻辑抽象到服务中,并在需要时将其注入。 这使应用程序更易于管理和测试。

Angular offers several useful services like $http, $log, $filter etc. The inbuilt services are always prefixed with $.

Angular提供了一些有用的服务,例如$ http,$ log,$ filter等。内置服务始终以$为前缀。

In this AngularJS services tutorial, we will create our own angular service.

在此AngularJS服务教程中,我们将创建自己的角度服务。

创建和注册Angular服务 (Creating and Registering Angular Services)

Angular services are created by registering them with the module they are going to operate in.

Angular服务是通过将其注册到要在其中运行的模块来创建的。

There are three ways to create an angular service. They are using Factory, Service and Provider.

有三种创建角度服务的方法。 他们正在使用Factory,Service和Provider。

First, create a module named app using the following syntax:

首先,使用以下语法创建名为app的模块:

var app = angular.module("app", []);

使用Factory的AngularJS服务 (AngularJS services using Factory)

The most common way to create a service is by using the Module’s Factory API. We use the factory method to create an object, add properties to it and return the same object. Later it can be injected to the components like controller, service, filter or directive.

创建服务的最常见方法是使用模块的Factory API。 我们使用工厂方法创建对象,向其添加属性并返回相同的对象。 以后可以将其注入到控制器,服务,过滤器或指令之类的组件中。

Here is the general syntax for using Factory service.

这是使用Factory服务的常规语法。

app.factory('factoryName',function(){
         return factoryObj;
      });

使用服务创建角度服务 (Create angular services using Service)

This is instantiated with the new keyword. You will be provided with an instance of the function passed to the service. This object instance becomes the service object that AngularJS registers and is injected to the required components.

这是用new关键字实例化的。 您将获得传递给服务的函数实例。 该对象实例成为AngularJS注册的服务对象,并注入到所需的组件中。

We use this keyword to add properties and functions to this service object. Unlike factory method, this does not return anything.

我们使用此关键字将属性和功能添加到该服务对象。 与工厂方法不同,此方法不返回任何内容。

Here is the general syntax for using Service.

这是使用Service的一般语法。

app.service('serviceName',function(){ });

使用提供程序的AngularJS服务示例 (AngularJS services example using Provider)

Providers are the only service you can pass into your .config() function. Providers are used when you want to provide module-wide configuration for your service object before making it available. It returns value by using $get() function.

提供程序是您可以传递给.config()函数的唯一服务。 如果要在服务对象可用之前为其提供模块范围的配置,则使用提供程序。 它使用$ get()函数返回值。

Here is the general syntax for creating and configuring a Provider.

这是创建和配置Provider的一般语法。

// syntax for creating a provider
app.provider('providerName',function(){ });

//syntax for configuring a provider
app.config(function(providerNameProvider){});

AngularJS服务示例 (AngularJS Services Example)

The following example demonstrates the usage of factory, service and provider services. We are going to develop a sample message service, which prints out a message using all these service APIs.

下面的示例演示工厂,服务和提供者服务的用法。 我们将开发一个示例消息服务,该服务将使用所有这些服务API打印出一条消息。

The code shown below (index.html) is our view. We need to get the serviceMsg, factoryMsg and providerMsg using the Service APIs and we use controller to wire the data to this view.

下面显示的代码(index.html)是我们的视图。 我们需要使用Service API获取serviceMsg,factoryMsg和providerMsg ,并使用控制器将数据连接到该视图。

<html>
<head>
    <title>AngularJS Services Tutorial</title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.12/angular.min.js"></script>
    <script src="main.js"></script>
</head>
<body>
<div>
    <div ng-app="mainApp" ng-controller="myController">
        <p><b>Message From Service: </b>{{serviceMsg}}</p>
        <p><b>Message From Factory: </b>{{factoryMsg}}</p>
        <p><b>Message From Provider:</b>{{providerMsg}}</p>
    </div>
</div>

</body>
</html>

The code shown below defines the services and the controller used in the application.

下面显示的代码定义了应用程序中使用的服务和控制器。

main.js

main.js

var app = angular.module('mainApp', []);

//define a service named myService
app.service('myService', function () {
    this.message = '';
    this.setMessage = function (newMessage) {
        this.message = newMessage;
        return this.message;
    };
});

//define factory  named 'myFactory'
app.factory('myFactory', function () {
    var obj = {};
    obj.message = '';
    obj.setMessage = function (newMessage) {
        obj.message = newMessage;
    };
    return obj;
});

//Defining a provider 'configurable'
app.provider('configurable', function () {
    var returnMessage = '';
    this.setMessage = function (newMessage) {
        returnMessage = newMessage;
    };
    this.$get = function () {
        return {
            message: returnMessage
        };
    };
});

//configuring provider
app.config(function (configurableProvider) {
    configurableProvider.setMessage("Hello, I'm From Provider");
});

//defining controller
app.controller('myController', function ($scope, myService, myFactory, configurable) {
    $scope.serviceMsg = myService.setMessage("Hello, I'm From Service");

    myFactory.setMessage("Hello, I'm From Factory ");
    $scope.factoryMsg = myFactory.message;

    $scope.providerMsg= configurable.message;
});

AngularJS服务示例代码说明 (AngularJS Services Example code description)

  1. Created a module named mainApp using angular.module(‘mainApp’, []);

    使用angular.module('mainApp',[]);创建了一个名为mainApp的模块
  2. Defined a service using service method in the module and you can see how we added properties and function to the service object for getting the message. We used this keyword to add the properties to the service object.

    在模块中使用service方法定义了服务,您可以看到我们如何向服务对象添加属性和功能以获取消息。 我们使用this关键字将属性添加到服务对象。
  3. Defined a service using factory method in the module and returned the service object.

    在模块中使用工厂方法定义了服务,并返回了服务对象。
  4. Defined a service using provider method in the module and used $get() function to get the message.

    在模块中使用提供者方法定义了服务,并使用$ get()函数获取消息。
  5. Configured the provider using the config() function in the module to set the message.

    使用模块中的config()函数配置提供程序以设置消息。
  6. Defined a controller and all the services are injected to the controller.

    定义了一个控制器,并将所有服务注入到该控制器。
  7. Set the factory and service messages.

    设置出厂和维修信息。
  8. Finally controller wire all the messages to the view using $scope.

    最后,控制器使用$ scope将所有消息连接到视图

输出量 (Output)

You will see the following output in your browser for our example services in AngularJS.

对于AngularJS中的示例服务,您将在浏览器中看到以下输出。

That’s all for services in AngularJS and we will see more angular features in the coming posts.

这就是AngularJS中所有服务的内容,我们将在以后的文章中看到更多的角度功能。

翻译自: https://www.journaldev.com/6685/angularjs-services-example-tutorial

angularjs 实例

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值