核心提示:内置方法 方法名 对应请求 get GET save POST query GET(返回数据需为数组) remove DELETE delete DELETE 基本写法s...
内置方法
| 方法名 | 对应请求 |
|---|---|
| get | GET |
| save | POST |
| query | GET(返回数据需为数组) |
| remove | DELETE |
| delete | DELETE |
基本写法
services代码
//将AboutService这个服务绑定到about.services这个module上
angular
.module('about.services')
.service('AboutService', aboutService);
//使用依赖注入将$resource服务注入到aboutService这个服务上
aboutService.$inject = ['$resource'];
//此时aboutService支持的方法(请求)有get/save/query/remove/delete
function aboutService($resource) {
return $resource('/app/about');
}
在控制器中使用这个services
controller代码
AcademicService.query(function(result){
//result即为我们使用query方法请求到的资源
})
自动匹配ID
对于以下api,因为只相差一个id,
'/app/academic' '/app/academic/:academicId'
我们只需将services代码作如下修改,就能全部一起
angular
.module('about.services')
.service('AboutService', aboutService);
aboutService.$inject = ['$resource'];
function aboutService($resource) {
return $resource('/app/about',{
academicId: '@_id'
});
}
相应的controller使用这两种API方法如下
controller代码
AcademicService.query(function(result){
//result即为我们使用query方法请求到的资源
})
//多传入一个academic即可
AcademicService.delete({academicId:academicId},function(result){
//result即为我们使用query方法请求到的资源
})
自定义方法
对于$resouce中没有内置的方法,比如(put,patch),需要我们自己定义。
比如我们需要扩展一个PUT方法,
angular
.module('about.services')
.service('AboutService', aboutService);
aboutService.$inject = ['$resource'];
function aboutService($resource) {
return $resource('/app/about',{
academicId: '@_id'
},{
update: {
method: 'PUT'
}
});
}
controller中调用的示例如下
- update方法,第一个参数为对象ID,第二个对象为对象本身
- delete方法,只有一个参数为对象ID
AcademicService.update(vm.academicInfo._id, vm.academicInfo, function (result) {
$modal.close('update');
});
AcademicService.delete({academicId: vm.academicInfo._id}, function () {
$modal.close('delete');
});
无法统一包含的API
最后提一点,如果你的API是像以下这样,api前半部分不是一致的,那就没办法写在一个services里(如果有,请各位大神告诉我),就直接用两个两个services搞定好了。
'/app/about' '/app/academic' '/app/academic/:academicId'
多个services的demo
angular
.module('about.services')
.service('AboutService', aboutService)
.service('AcademicService', academicService);
aboutService.$inject = ['$resource'];
function aboutService($resource) {
return $resource('/app/about',{
academicId: '@_id'
},{
update: {
method: 'PUT'
}
});
}
aboutService.$inject = ['$resource'];
function aboutService($resource) {
return $resource('/app/about', {}, {
update: {
method: 'PUT'
}
});
}


