on  it road.com

使用 - module.service( 'serviceName', function(){} )

当我们使用 module.service()创建服务时,作为第二个参数传递的 function() 实例成为 AngularJS 注册的服务对象,并在需要时注入其他服务/控制器。

使用module.service()在自定义服务对象中声明方法的语法是:

module.service('DemoService', function() {
	//"this" will be used as service instance
    this.firstMethod = function() {
        //..
    }

    this.someOtherMethod = function() {
        //..
    }
});

内置 Angular 服务

如前所述,angular 提供了几个可以即时使用的内置服务。
在运行时,这些服务会自动向依赖注入器注册,因此我们可以使用依赖注入轻松地将它们合并到 Angular 应用程序中。
例如,要在控制器中使用 $http服务,请按如下方式注入服务:

module.controller('DemoController', function( $http ){
    //...
});

让我们列出 Angular 内置服务。

服务名称描述
$anchorScroll提供滚动到$location.hash()中指定的页面锚点的能力
$animate该服务公开了一系列为动画钩子提供支持的 DOM 实用程序方法。
$animateCss默认情况下,只有当包含 ngAnimate时,该服务才会执行动画。
$cacheFactory构造 Cache 对象、放置和检索键值对并为其提供对其他服务的访问权限的工厂。
$templateCache第一次使用模板时,它会加载到模板缓存中以便快速检索。
$compile将 HTML 字符串或者 DOM 编译为模板并生成模板函数,然后可以使用该函数将作用域和模板链接在一起。
$controller这负责实例化Angular控制器组件。
$document指定对 window.document元素的 jQuery 包装引用。
$exceptionHandlerAngular表达式中任何未捕获的异常都委托给此服务。默认实现只是委托给$log.error,它将它记录到浏览器控制台中。
$filter过滤器用于格式化显示给用户的数据。
$httpParamSerializer将对象转换为字符串的默认 $httpparams 序列化程序。
$httpParamSerializerJQLike遵循 jQuery 的 param()方法逻辑的替代 $httpparams 序列化程序。序列化程序还将按字母顺序对参数进行排序。
$http此服务通过浏览器的“XMLHttpRequest”对象或者通过“JSONP”促进与远程 HTTP 服务器的通信。
$xhrFactory用于创建 XMLHttpRequest对象的工厂函数。
$httpBackend用于处理浏览器不兼容。
$interpolate将带有标记的字符串编译为插值函数。这个服务被 HTML $compile服务用于数据绑定。
$intervalwindow.setInterval的 Angular 包装器。
$locale为各种 Angular 组件提供本地化规则。
$location它解析浏览器地址列中的 URL 并使该 URL 可用于应用程序。地址列中 URL 的更改会反映到 $location服务中,而对 $location的更改会反映到浏览器地址列中。
$log控制台记录器。
$parse将 Angular 表达式转换为函数。
$q异步运行函数,并在完成处理后使用它们的返回值(或者错误)。
$rootElementAngular 应用程序的根元素。
$rootScope范围提供模型和视图之间的分离。这是针对根范围的。每个应用程序都有一个根范围。
$sceDelegate由后端的$sce使用。
$sce为 AngularJS 提供严格的上下文转义服务。
$templateRequest它运行安全检查,然后使用 $http下载提供的模板,并在成功后将内容存储在 $templateCache中。
$timeoutwindow.setTimeout()的 Angular 包装器
$window对浏览器的“window”对象的引用。虽然 window在 JavaScript 中是全局可用的,但它会导致可测试性问题,因为它是一个全局变量。在 angular 中,我们总是通过 $window服务来引用它,因此它可能会被覆盖、删除或者模拟以进行测试。

参考:https://docs.angularjs.org/api/ng/service

Angular 服务

服务是无状态的单例对象,为 Web 应用程序提供功能。

例如,$http是对 Web 服务器进行 HTTP 调用的核心服务。
简单来说,我们可以将 Angular 服务视为执行一个或者多个相关任务的可重用代码块(例如 Java 中具有静态方法的实用程序类)。
在 AngularJS 中,有几个内置服务,我们也可以创建自己的自定义服务。

如何使用 AngularJS 服务

此示例演示了自定义服务的使用,该服务具有在不同时区显示当前时间的逻辑。
让我们首先创建自定义服务。

var app = angular.module('myApp', []);
//Create a function
function TimeObj() {
    var cities = {
        'Los Angeles': -8,
        'New York': -5,
        'London': 0
    };
    this.getTZDate = function(city) {
        var localDate = new Date();
        var utcTime = localDate.getTime() + localDate.getTimezoneOffset() * 60 * 1000;
        return new Date(utcTime + (60 * 60 * 1000 * cities[city]));
    };
    this.getCities = function() {
        var cList = [];
        for (var key in cities) {
            cList.push(key);
        }
        return cList;
    };
}
//Register as service 'TimeService'
app.service('TimeService', [TimeObj]);

现在要使用此服务,请使用如下控制器:

app.controller('LAController', ['$scope', 'TimeService',
    function($scope, timeS) {
        $scope.myTime = timeS.getTZDate("Los Angeles").toLocaleTimeString();
    }
]);
app.controller('NYController', ['$scope', 'TimeService',
    function($scope, timeS) {
        $scope.myTime = timeS.getTZDate("New York").toLocaleTimeString();
    }
]);
app.controller('LondonController', ['$scope', 'TimeService',
    function($scope, timeS) {
        $scope.myTime = timeS.getTZDate("London").toLocaleTimeString();
    }
]);

现在我们可以在网页中使用控制器来显示不同的时间。

<html ng-app="myApp">
	<head>
		<title>AngularJS Custom Time Service</title>
		<style>
			span {
				color: lightgreen; background-color: black;
				border: 3px ridge; padding: 2px;
				font: 14px/18px arial, serif; 
			}
		</style>
	</head>
	<body>
		<h2>Custom Time Service:</h2><hr>
		<div ng-controller="LAController">
		Los Angeles Time:
		<span>{{myTime}}</span>
		</div><hr>
		<div ng-controller="NYController">
		New York Time:
		<span>{{myTime}}</span>
		</div><hr>
		<div ng-controller="LondonController">
		London Time:
		<span>{{myTime}}</span>
		</div>
	</body>
</html>

使用 - module.factory( 'factoryName', function(){} )

当我们使用 module.factory()创建服务时,作为第二个参数传递的 function() 的返回值成为 AngularJS 注册的服务对象,并在需要时注入其他服务/控制器。

使用module.factory()在自定义服务对象中声明方法的语法是:

module.factory('DemoService', function() {
	//"factory" will be used as service instance
	var factory = {}; 
    factory.firstMethod = function() {
        //..
    }

    factory.someOtherMethod = function() {
        //..
    }
    return factory;
});

创建自定义 Angular 服务

将应用程序的业务逻辑和通用操作放在一个地方,总是一个好的设计。
这提高了代码的可重用性并避免了代码重复。
我们应该将所有这些逻辑放在自定义Angular服务中。
这使得代码模块化且更易于维护。

此外,代码变得更加可测试。
请记住,angular 为单元测试提供了一流的支持。
因此,我们可以快速为这些服务编写测试并避免许多可能的缺陷。

主要有两种方式来声明 angularjs 服务。
让我们理解两种方式:

日期:2020-09-17 00:09:14 来源:oir作者:oir