AngularJS基础教程

自定义服务

前言

AngularJS 提供了几种实现自定义服务的方式:provider、factory、service。
使用 factory 的方式是对使用 provider 的方式的再次封装,使用 service 的方式是对使用 factory 的方式的再次封装。本章节只讲解了使用 service 实现自定义服务的方式。

为什么要使用自定义服务

在之前章节我们的示例代码中,大量功能代码均写在 Controller 中,不仅使代码不易于维护,也降低了代码的可复用性。

如果将一类数据作为一个服务提供,则可解决此问题。

例如,可为“用户”创建一个服务,所有有关“用户”的操作都封装在此服务中。

如何创建自定义服务

先来看看如何用 service 创建自定义服务。

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>自定义服务</title>
<script src="js/angular.min.js"></script>
</head>
<body>
<div ng-app="myApp" ng-controller="myController">
{{name}}
</div>
<script type="text/javascript">
var app = angular.module('myApp', []);
app.service('myService', function () {
this.name = 'CYF';
});
app.controller('myController', function ($scope, myService) {
$scope.name = myService.name;
});
</script>
</body>
</html>

来分析一下这段代码:

app.service() 创建了一个名为“myService”的服务,第一个参数为要创建的服务的名字,第二个参数为服务的具体实现。这段代码实际上是定义了一个名为“myService” class

app.controller() 的第二个参数 function 中,声明要使用“myService”这个服务,实际上是创建了一个“myService” class 的实例。

参考下面这段代码,与上面的代码是等效的:

var app = angular.module('myApp', []);
app.controller('myController', function ($scope) {
var myService = function(){
this.name = 'CYF';
};
var svc = new myService();
$scope.name = svc.name;
});

创建并使用“用户”服务的例子

这是一个对我们系统的用户进行管理的例子。将所有用户展示出来,每条用户数据后面有个“删除”按钮,点击后能将该条用户数据删除。

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>自定义服务</title>
<script src="js/angular.min.js"></script>
</head>
<body>
<div ng-app="myApp" ng-controller="myController">
<ul>
<!-- 注意这里使用的是 users.lst, -->
<!-- 因为 Users 服务的 getAll() 返回的是 Users 的实例,而不是用户列表,用户列表是该实例的 lst 属性 -->
<li ng-repeat="item in users.lst">{{item.name}}({{item.id}}) -- <button ng-click="del()">删除</button></li>
</ul>
</div>
<script type="text/javascript">
var app = angular.module('myApp', []);
// 创建了一个名为 Users 的服务
app.service('Users', function ($http) {
var _this = this;
// 获取所有用户。是非公开的方法
var query = function () {
$http.get('/api/users/gets').success(function (result) {
_this.lst = result.data; // 将返回的所有用户数据保存在 this.lst
});
};
// 获取所有用户。对外公开的方法
this.getAll = function () {
if (!this.lst) { // 先判断 this.lst 有没有值,如果没有,才调用 query() 去取得所有的用户数据
query();
}
return this; // 注意这里返回的是 this,而不是 this.lst。这样做的好处是避免了写回调方法。在做数据绑定时需使用返回值的 lst 属性
};
// 删除指定的用户
this.remove = function (id) {
$http.post('/api/users/remove', { id: id }).success(function () {
// 删除成功后,应在本地的用户列表数据(this.lst)中也将该用户删除,
// AngularJS 会自动将页面上相应的用户数据删除
if (_this.lst) {
_this.lst = _this.lst.filter(function (item) {
return item.id != id;
});
}
});
};
});
app.controller('myController', function ($scope, Users) {
$scope.users = Users.getAll();
$scope.del = function () {
Users.remove(this.item.id);
};
});
</script>
</body>
</html>

从以上代码可以看出,Controller 中的代码要简洁多了。在 Controller 中不用关心服务的具体实现,只需调用服务所提供的方法即可。

最后,来个广告

若你觉得此文不错,请分享,若认为尚需改进,请点讚。

结束语