原文: https://learnable.com/books/angularjs-novice-to-ninja/preview/understanding-angularjs-resource-e0638c0

多数AngularJS应用都需要一些CRUD操作. 你可以使用$resource服务快速的进行一个CRUD.

前提

$resource服务不包含在angular.js中. 因为不是每个Angular应用都需要CRUD操作, 如果你需要使用$resource服务你必须首先引用angular-resource.js文件.

然后你需要把ngResource注入到你的app中:

1
angular.module('myApp',  ['ngResource']);

我们这样做是因为$resource服务定义在ngResource模块中.

$resource是怎么工作的?

$resource和RESTful API工作. 这意味着你的的URLS应该类似于下面的模式

URL HTTP Verb Request Body Result
/api/entries GET empty Returns all entries
/api/entries POST JSON String Creates new entry
/api/entries/:id GET empty Returns single entry
/api/entries/:id PUT JSON String Updates existing entry
/api/entries/:id DELETE empty Deletes existing entry

为了在你的controller或者service中使用 $resource, 你需要声明一个对$resource的依赖. 下面的代码展示了如何在你的自定义服务中使用$resource:

1
2
3
angular.module('myApp').factory('Entry', fucntion($resource){
    return $resource('/api/entries/:id');
});

$resource默认有5个方法:

  1. get()

  2. query()

  3. save()

  4. remove()

  5. delete()

现在来看看怎么使用这些方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
angular.module('myApp').controller('ResourceController',
  function($scope, Entry) {
    var entry = Entry.get({ id: $scope.id }, function() {
      console.log(entry);
    }); // get() 返回单个entry
 
    var entries = Entry.query(function() {
      console.log(entries);
    }); //query() 返回所有的entry
 
    $scope.entry = new Entry(); //你可以实例化一个resource类
 
    $scope.entry.data = 'some data'// $scope.entry= {data:'some data'}
 
    Entry.save($scope.entry, function() {
          //把$scope.entry序列化成一个JSON作为POST body
    });
 
    Entry.delete({ id: $scope.id }, function() {
      console.log('Deleted from server');
    });
});

get() 函数发起了一个GET请求 /api/entries/:id.  在发送前我们把:id赋值为$scope.id. 注意了get()函数返回了一个空对象. 当数据从服务器返回的时候会自动填充到这个空对象. get()函数的第二个方法会在数据从服务器返回的时候执行. 你可以在这里把返回值赋值给$scope.

为什么使用空对象?

You might question the wisdom of showing an empty object initially. Actually it's a good thing because you can omit the callback passed toget() function. 如果你只是想把model赋值给$scope而不关心数据是什么时候从服务器返回的, 你可以使用下面的方法:

1
$scope.entry = Entry.get({ id: $scope.id });

如果get不返回一个空对象的话, 你需要添加一个callback:

1
2
3
Entry.get({id: $scope.Id}, function(entry){
    $scope.entry = entry;
);

query()对/api/entries 发起了一个get请求(注意了没有:id) 并返回一个空数组 (不是一个简单的对象). 当数据从服务器返回的时候这个空对象会被填充.

save()对 /api/entries 发起了一个post请求. 第一个参数是POST body. 第二个参数是callback, 当数据保存完成后触发. You might recall that the return value of the $resource() function is a resource class. So, in our case, we can call new Entry() to create an actual resource instance, set various properties to it and finally save the object to the back end.

delete() 和 remove() 都对/api/entries/:id发起一个delete请求

使用 remove() 兼容IE

有些IE浏览器可能不支持delete(). 可以使用remove兼容IE.

在resource类中我们只使用get() query() (在我们的例子中resource类是Entry). 所有非GET的方法, 例如 save()和 delete()在 new Entry()的实例中能用 (在这我们把它称为 $resource 实例). 不同的是这些方法以$开头

1
2
3
$save()
$delete()
$remove()

看看$save()方法是怎么使用的:

1
2
3
4
$scope.entry = new Entry();//这个对象有个$save()方法
$scope.entry.$save(function(){
    console.log('data saved');
}); // $scope.entry 序列化成JSON作为POST body被发送

为了支持update操作, 我们需要修改代码如下

1
2
3
4
5
6
7
angular.module('myApp').factory('Entry'function($resource){
    return $resource('/api/entries/:id', {id:'@_id'},{
        update: {
          method: 'PUT'
        }
    });
});

$resource()的第二个指示url的:id参数的值应该是什么. 这里设置为@_id, 当你调用$resource实例的$delete()和$update()的时候, :id的值会被设置为实例的_id属性. 这个是为PUT和DELETE请求使用的. 注意第三个参数. 这是一个map允许我们给resource类添加自定义的方法. 如果方法不是一个get请求的话, $resource实例会有一个以$开头的同名方法. 现在看看怎么使用$update方法:

1
2
3
4
5
6
7
$scope.entry = Entry.get({id:$scope.id}, function(){
    //$scope.entry 是服务器返回来的 是一个Entry的实例
    $scope.entry.data = 'something else';
    $scope.entry.$update(function(){
        console.info('updated');
    });
});

当$update被调用, 会发生下面的东西:

  1. AngularJS 知道$update()会触发一个对/api/entries/:id的PUT请求.

  2. 读取$scope.entry._id并将赋值给url的:id参数.

  3. 将$scope.entry作为一个请求体PUT个URL.

同样, 如果你想删除一个entry你可以这样做:

1
2
3
4
5
$scope.entry = Movie.get({id: $scope.id}, function(){
    $scope.entry.$delete(function(){
        //completed
    });
});

使用 MongoDB

如果你使用的是MongoDB, 你从后端获取到的$scope.entry实例通常有一个叫_id的属性. { id: '@_id' } 当调用$update()或者$delete()的时候, url的:id参数会被赋值为实例的_id属性 .

$resource第四个参数是可选的. 它是一个客户自定义的配置. 这里我们只设置 stripTrailingSlashes. 默认情况下它的值是true, 这意味他会自动去除url的最后一个/. 如果你不想这样可以这样:

1
2
3
4
5
6
7
8
9
angular.module('myApp').factory('Entry'function($resource) {
  return $resource('/api/entries/:id', { id: '@_id' }, {
    update: {
      method: 'PUT' // this method issues a PUT request
    }
  }, {
    stripTrailingSlashes: false
  });
});

  

了解AngularJS $resource的更多相关文章

  1. Spring resource bundle多语言,单引号format异常

    Spring resource bundle多语言,单引号format异常 前言 十一假期被通知出现大bug,然后发现是多语言翻译问题.法语中有很多单引号,单引号在format的时候出现无法匹配问题. ...

  2. Spring5:@Autowired注解、@Resource注解和@Service注解

    什么是注解 传统的Spring做法是使用.xml文件来对bean进行注入或者是配置aop.事物,这么做有两个缺点: 1.如果所有的内容都配置在.xml文件中,那么.xml文件将会十分庞大:如果按需求分 ...

  3. 【初探Spring】------Spring IOC(三):初始化过程---Resource定位

    我们知道Spring的IoC起到了一个容器的作用,其中装得都是各种各样的Bean.同时在我们刚刚开始学习Spring的时候都是通过xml文件来定义Bean,Spring会某种方式加载这些xml文件,然 ...

  4. 2000条你应知的WPF小姿势 基础篇<34-39 Unhandled Exceptions和Resource>

    在正文开始之前需要介绍一个人:Sean Sexton. 来自明尼苏达双城的软件工程师.最为出色的是他维护了两个博客:2,000Things You Should Know About C# 和 2,0 ...

  5. 【解决方案】 org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userHandler': Injection of resource dependencies failed;

    一个错误会浪费好多青春绳命 鉴于此,为了不让大家也走弯路,分享解决方案. [错误代码提示] StandardWrapper.Throwableorg.springframework.beans.fac ...

  6. AngularJS Resource:与 RESTful API 交互

    REST(表征性状态传输,Representational State Transfer)是Roy Fielding博士在2000年他的博士论文中提出来的一种软件架构风格.RESTful风格的设计不仅 ...

  7. 运行nltk示例 Resource u'tokenizers punkt english.pickle' not found解决

    nltk安装完毕后,编写如下示例程序并运行,报Resource u'tokenizers/punkt/english.pickle' not found错误 import nltk sentence ...

  8. Android LayoutInflater.inflate(int resource, ViewGroup root, boolean attachToRoot)的参数理解

    方法inflate(int resource, ViewGroup root, boolean attachToRoot) 中 第一个参数传入布局的资源ID,生成fragment视图,第二个参数是视图 ...

  9. ORA-00054: resource busy and acquire with NOWAIT specified

    删除表时遇到 ORA-00054:资源正忙,要求指定NOWAIT 错误.以前在灾备中心遇到过. 资源被锁定了,没有办法删除. 报错日志:ORA-00054: resource busy and acq ...

  10. angular学习笔记(二十八-附1)-$resource中的资源的方法

    通过$resource获取到的资源,或者是通过$resource实例化的资源,资源本身就拥有了一些方法,$save,$delete,$remove,可以直接调用来保存该资源: 比如有一个$resour ...

随机推荐

  1. 1064. Complete Binary Search Tree

    二叉排序树: http://www.patest.cn/contests/pat-a-practise/1064 #include <iostream> #include <vect ...

  2. 去掉代码中自动生成的TODO Auto-generated method stub

    Window --> Preferences -->Java -->Code Style -->Code Templates--> Code --> Method ...

  3. IOS开发之表视图添加索引

    我们要实现的效果如下. 1.修改ControlView.h,即添加变量dict,用于存储TabelView的数据源. #import <UIKit/UIKit.h> @interface  ...

  4. MVC视图引擎

    1.视图引擎:把视图解析成浏览器可执行的html代码 2.aspx视图: <%=表达式%>: <% C#代码段 %>: 3.razor视图: @(表达式):@ViewData[ ...

  5. 1201: [HNOI2005]数三角形 - BZOJ

    Description Input 大三角形的所有短边可以看成由(n+1)*n/2个单位三角形的边界组成.如下图的灰色三角形所示.其中第1排有1个灰色三角形,第2排有2个灰色三角形,……,第n排有n个 ...

  6. js和HTML结合(补充知识:如何防止文件缓存的js代码)

    来自<javascript高级程序设计 第三版:作者Nicholas C. Zakas>的学习笔记(二) 使用html标签<script>可以把js嵌入到html页面中,让脚本 ...

  7. [转载]MongoDB优化的几点原则

    .查询优化 确认你的查询是否充分利用到了索引,用explain命令查看一下查询执行的情况,添加必要的索引,避免扫表操作. .搞清你的热数据大小 可能你的数据集非常大,但是这并不那么重要,重要的是你的热 ...

  8. spoj 39

    DP  完全背包问题 的   d[i] = min(d[i], d[i-w]+p)   d[i]表示当总重量为i时可装的最小价值 #include <cstdio> #include &l ...

  9. hdu 3778

    简单的dfs  但繁琐的可以了 0.0 #include<cstdio> #include<cstring> #include<algorithm> using s ...

  10. 10 things you should know about NoSQL databases

    For a quarter of a century, the relational database (RDBMS) has been the dominant model for database ...