AngularJS基础教程

ngResource

前言

ngResource 模块对 AngularJS 中的 $http 进行了再次封装,可让开发者更方便地使用 RESTful。

什么是RESTful

RESTful 是一种架构设计风格。在一般应用中,绝大部分功能是“增、删、改、查”。RESTful 风格的服务提供的 API 中,一个的 URL 地址表示一种资源,用标准的 HTTP 请求方法(PUT、DELETE、POST、GET)表示应该进行何种操作(增、删、改、查)。

例如,可以这样设计对“用户”进行操作的 API。将 API 地址设计为这样:

/api/users/9527

如果用 GET 方法访问该接口,则会获得 ID 为 9527 的用户的信息;如果用 DELETE 方法访问该接口,则删除 ID 为 9527 的用户;如果用 PUT,则表示修改;如果用 POST,则表示新增。

如何获得 ngResource

点击这里到官网查找获得 ngResource 的方法。

使用 npm 获得 ngResource 的方法:

npm install angular-resource

也可以指定版本号:

npm install angular-resource@X.Y.Z

X.Y.X 替换为你想要的版本号即可。

调用非 RESTful API

大多数 Server 端提供的 API 都不是按 RESTful 设计的,ngResource 当然也可以用来调用非 RESTful 的 API。我们先来看看使用 ngResource 调用非 RESTful API 的例子:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>ngResource</title>
<script src="js/angular.min.js"></script>
<script src="js/angular-resource.min.js"></script>
</head>
<body>
<div ng-app="myApp" ng-controller="myController">
<!-- API 返回的数据为 {err:0, data:{id:200, name:"许文强", ....}},并赋值给了 $scope.result, -->
<!-- 因此这里可以用 result.data.name -->
<div>{{result.data.name}}</div>
</div>
<script type="text/javascript">
var app = angular.module('myApp', ['ngResource']);
app.controller('myController', function ($scope, $resource) {
// 创建了一个 resource 的实例,API 地址为 '/api/users/get'
var res = $resource('/api/users/get');
// 使用 GET 方法调用该 API,并传递了参数 id
// 将 API 的返回结果赋值给 $scope.result,这样就能在 HTML 对其进行数据绑定了
$scope.result = res.get({ id: 200 });
});
</script>
</body>
</html>

ngResource 当然也是使用的 AJAX,那么当然也是异步的。但这里却直接将 res.get() 的返回值赋值给了 $scope.result,因此刚开始时 $scope.result.data 是没有值的,所以不能这样子做:

var result = res.get({ id: 200 });
$scope.user = result.data; // 此时 result.data 的 undefined

然后在 HTML 中这样写:

<div>{{user.name}}</div>
这样做的话在网页中将无法显示“用户名”。这是因为 $scope.userundefinedresult 中的数据改变与 $scope.user 无关。

还可以用类似 jQuery 的回调语法:

res.get({ id: 200 }, function (result) { // 成功后执行此 function
$scope.result = result;
}, function(err){ // 失败后执行此 function
console.log('ERROR:', err);
});

如果要提交数据,则使用 save 方法:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>ngResource</title>
<script src="js/angular.min.js"></script>
<script src="js/angular-resource.min.js"></script>
</head>
<body>
<div ng-app="myApp" ng-controller="myController">
<div>修改指定用户的年龄:</div>
<div>用户ID:<input type="number" ng-model="id" /></div>
<div>新的年龄:<input type="number" ng-model="age" /></div>
<div>
<button ng-click="submit()">提交</button>
</div>
<div ng-bind="msg"></div>
</div>
<script type="text/javascript">
var app = angular.module('myApp', ['ngResource']);
app.controller('myController', function ($scope, $resource) {
$scope.submit = function () {
var id = parseInt($scope.id), age = parseInt($scope.age);
if (id && age) {
var res = $resource('/api/users/update');
// save() 方法会发送 post 请求
res.save({ id: id, age: age }, function (result) { // 成功后执行此 function
$scope.msg = result.err == 0 ? '成功' : '发生错误了';
}, function(err){ // 失败后执行此 function
console.log('ERROR:', err);
});
}
};
});
</script>
</body>
</html>

调用 RESTful API

要调用 RESTful API,显然需要你的 Server 端有提供这样的接口。在我们的测试服务器中已提供了这样的接口。

以下是一个简单的示例:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>ngResource</title>
<script src="js/angular.min.js"></script>
<script src="js/angular-resource.min.js"></script>
</head>
<body>
<div ng-app="myApp" ng-controller="myController">
<button ng-click="togglerShowAdd()">新增用户</button>
<!-- “新增用户”的面板,由“isShowAdd”来控制是否展示出来 -->
<div ng-show="isShowAdd" style="padding:3px 10px;background-color:#f6f6f6">
姓名:<input type="text" ng-model="name" /><br />
年龄:<input type="number" ng-model="age" /><br />
<button ng-click="add()">提交</button>
</div>
<hr />
<!-- 用户列表 -->
<ul>
<li ng-repeat="item in users">{{item.name}}({{item.id}})--<button ng-click="del()">删除</button></li>
</ul>
</div>
<script type="text/javascript">
var app = angular.module('myApp', ['ngResource']);
app.controller('myController', function ($scope, $resource) {
$scope.isShowAdd = false; // isShowAdd 用来控制“新增用户”的面板是否展示出来
$scope.togglerShowAdd = function () { // 点击“新增用户”按钮后,切换“新增用户”面板的展示状态
$scope.isShowAdd = !$scope.isShowAdd;
};
// 创建了一个 resource 的实例,API 地址为“/rest/users/:id
// 其中,:id 是一个占位符,当调用时参数中有 id 参数时,则会用所传参数的值替换此位置
var res = $resource('/rest/users/:id');
// 使用 query() 方法取出所有的用户
// 发送的请求为:GET /rest/users/
$scope.users = res.query();
// 新增用户
$scope.add = function () {
var name = $scope.name, age = parseInt($scope.age);
if (name && age) {
// 使用 save() 将填写的用户信息发送到服务器,
// save() 会发送 post 请求
// 发送的请求为:post /rest/users/ 参数:name=name; age=age
res.save({
name: name,
age: age
}, function (result) { // 成功后执行此 function
if (result.err == 0) { // 如果新增用户成功,则在 $scope.users 中新增一条数据,使新数据能显示在列表中
$scope.users.unshift({
id: result.id,
name: name
});
}
});
}
};
// 删除指定的用户
$scope.del = function () {
// this.item 为当前被删除的用户的数据,因此可用 this.item.id 获得被删除用户的 ID
var id = this.item.id;
// 使用 delete() 方法删除一个用户
// 发送的请求为:DELETE /rest/users/id
res.delete({ id: this.item.id }, function (result) { // 成功后执行此 function
// 删除用户成功后,将 $scope.users 中对应的数据也移除掉,使其在显示列表中也被删除掉
$scope.users = $scope.users.filter(function (item) {
return item.id != id;
});
});
};
});
</script>
</body>
</html>

代码中有详细的注释说明,注意查看。

最后,来个广告

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

结束语