restangular初体验
Restangular是一种AngularJS服务,可以使用最少的客户端代码简化常见的GET,POST,DELETE和UPDATE请求。它适用于任何从RESTful API中获取数据的WebApp。
可以从bower和npm包管理器中获取restangular,初次尝试也可以使用cdn
<scripttype="text/javascript"src="http://cdnjs.cloudflare.com/ajax/libs/restangular/1.5.1/restangular.js"></script><scripttype="text/javascript"src="http://cdnjs.cloudflare.com/ajax/libs/restangular/1.5.1/restangular.min.js"></script>
第一种是未压缩版,第二种是压缩版,相比前者压缩版体积更小。
//AddRestangularasadependencytoyourappangular.module('your-app',['restangular']);//InjectRestangularintoyourcontrollerangular.module('your-app').controller('MainCtrl',function($scope,Restangular){//...});
这里演示了如何加载restangular。
注入rest的时候要用小写,作为依赖的时候要大写,不然会报错。
//FirstwayofcreatingaRestangularobject.JustsayingthebaseURLvarbaseAccounts=Restangular.all('accounts');//Thiswillquery/accountsandreturnapromise.baseAccounts.getList().then(function(accounts){$scope.allAccounts=accounts;});
第一行代码声明了基础的路由地址,.getList()用于通过路由/accounts发起一次查询请求。
varnewAccount={name:"Gonto'saccount"};//POST/accountsbaseAccounts.post(newAccount);
向/accounts地址发送post请求,发送的数据为newAccount对象
//JustONEGETto/accounts/123/buildings/456Restangular.one('accounts',123).one('buildings',456).get()
one方法为向URL中追加参数,第一个参数是参数名,第二个是参数值,最终的get()决定了请求为get方式还是post方式。
当然one方法也可以不带参数名,比如像我项目中就有这么一行代码
functiondelete(id){Restangular.all('service').one(id).remove();}
这里请求为delete,向service发送删除请求,删除的id为XXX,最终形成的路由为
/service/`id`
暂时常用的是这些,如果有其他方式会另行补充。
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。