$resources
resources
2023-09-11 14:15:30 时间
安装
ngResource模块是一个可选的angularjs模块,如果需要使用,我们要单独引用js
<script type="text/javascript" src="/javascripts/angular-resource.js"></script>
应用$resource
我们并不是直接通过$resource服务本身同服务器通信,$resource是一个创建资源对象的工厂,用来创建同服务端交互的对象。
var User = $resource('/api/users/:userId', {userId:'@id'});
返回的User对象包含了同后端服务进行交互的方法,我们可以把User对象理解成同RESTFul的后端服务进行交互的接口。
该对象包含两个get类型的方法已经三个非get类型的方法。
User.get({id:'123'}, successFn, errorFn);
该方法向url发送一个get请求,并期望一个json类型的响应。这里会向/api/users/123发送一个请求,successFn处理请求成功响应,errorFn处理错误。
User.query(params, successFn, errorFn)
同get()方法使用类似,一般用来请求多条数据。
save(params, payload, successFn, errorFn);
save方法会发起一个post请求,params参数用来填充url中变量,对象payload会作为请求体进行发送
delete(params, payload, successFn,errorFn)
delete方法一个DELETE请求,payload作为消息体进行发送
remove(params, payload, successFn, errorFn)
同delete类似,不同的是remove用来移除多条数据
通过$resource生成的对象来同服务器进行交互的时候,我们看可以定义处理成功以及处理失败的函数,这些函数接受的参数不仅仅是简单的对象,而是经过包装之后的对象,会被添加$save(), $remove(), $delete三个方法,可以直接调用这三个方法来后服务端进行交互。
User.get({id:'123'}, function(user){ user.name = 'changeAnotherName'; user.$save(); //这里等价于User.save({id:'123'},{name:'changeAnotherName'}) });
扩展$resource
$resource对常见的五种请求进行封装,我们还可以对$resource进行扩展。
这里要扩展$resource我们需要传入第三个参数,该参数是一个对象。
$resource('/api/users',{},{ sendEmail:{ method:'', url:'', params:{}, isArray:boolean, transformRequest:函数或者函数数组 transformResponse:函数或者函数数组 cache:布尔型或缓存对象 timeout:数值或promise对象 withCredentials:布尔类型 responseType:字符串,用来设置XMLHttpRequestResponseType属性 } })
我们也可以将$resource服务当做自定义服务的基础。
angular.module('testApp', ['ngResource']),factory('UserService',['$resource', function($resource){ return $resource(url,{},{}); }]);
.
相关文章
- Error building Player: CommandInvokationFailure: Failed to re-package resources. See the Console for details. ShareSDK 也有这种错误
- java根据windows或者linux获取resources目录下的路径
- maven项目Java resources 上面有个红叉但是代码里面并没有什么报错
- 在 JDK 9 中更简洁使用 try-with-resources 语句
- 在 JDK 9 中更简洁使用 try-with-resources 语句
- Using platform encoding (GBK actually) to copy filtered resources, i.e. build is platform dependent!
- [PWA] Cache Third Party Resources from a CDN in a React PWA
- maven pom resources标签的使用示例
- Chrome开发者工具network标签页里的transferred over network和resources loaded by the page的区别
- 【错误记录】Android Studio 编译报错 ( Error: Duplicate resources | 使用 sourceSets 配置多个 res 资源不能有重复名称的资源 )
- 【Android 安装包优化】资源打包配置 ( resources.arsc 资源映射表 | 配置国际化资源 )
- maven项目建立pom.xml报无法解析org.apache.maven.plugins:maven-resources-plugin:2.4.3
- FPGA - 7系列 FPGA内部结构之Memory Resources -02- FIFO资源