Angular企业级开发(4)-ngResource和REST介绍
一、RESTful介绍RESTful维基百科
符合REST设计风格的Web API称为RESTful API。它从以下三个方面资源进行定义:
二、$resource介绍和使用
$resource服务主要用来处理使用RESTful编写后台的接口进行数据交互。
语法格式:
{ "get": { "method": "GET" },//一般用于获取某个资源 "query": { "method": "GET","isArray": true },//一般用于获取资源列表,以数组形式返回 "save": { "method": "POST" },//一般用于保存某个资源,有可能是新建的资源,也有可能是更新现有的资源 "remove": { "method": "DELETE" } //一般用于删除某个资源delete: {"method": 'DELETE'}一般用于删除某个资源 } demo: var blogModule = angular.module('blogModule',['ngResource']); blogModule.factory('BlogResource',['$resource',function ($resource) { return $resource(serverUrl + "/api/blog/:id",{},{ get: { method: 'GET',cache: false,isArray: false },save: { method: 'POST',update: { method: 'PUT',delete: { method: 'DELETE',isArray: false } }); }]); CRUD操作 blogModule.controller('BlogListCtrl',['$scope','BlogResource',function($scope,BlogResource) { BlogResource.get({},function (response) { $scope.blogList = response; },function (error) { console.log("Error:" + JSON.stringify(error)); }); //返回数据 // $scope.blogList = [ // { // "id": 1,// "date": 1400623623107,// "introText": "This is a blog post about AngularJS. We will cover how to build",// "blogText": "This is a blog post about AngularJS. We will cover how to build a blog and how to add comments to the blog post." // },// { // "id": 2,// "date": 1400267723107,// "introText": "In this blog post we will learn how to build applications based on REST",// "blogText": "In this blog post we will learn how to build applications based on REST web services that contain most of the business logic needed for the application." // } // ]; }]); blogModule.controller('BlogDetailCtrl','$routeParams',$routeParams,BlogResource) { var blogId = $routeParams.id; BlogResource.get({ id: blogId },function (response) { $scope.blogEntry = response; },function (error) { console.log("Error:" + JSON.stringify(error)); }); }]); 新建博客 //新建博客控制器 blogModule.controller('NewBlogPostCtrl',function ($scope,BlogResource) { $scope.submit=function(){ var postData={ "introText":$scope.introText,"blogText":$scope.blogText,"languageId":1 }; var blogId=Date.now(); BlogResource.save({ id: blogId },postData,function(response){ console.log("Success:"+JSON.stringify(response)); },function(errorResponse){ console.log("Error:"+JSON.stringify(errorResponse)); }); } }]); ps:前后端代码都写好之后,上传到Github上。http://angularjsblog.duapp.com/ 后端是Node.js编写。 三、参考资料
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
- angularjs – 延迟对象承诺和$resource服务的承诺之间的区别
- varnish cache 反向代理服务器和http加速器的安装和配置
- [译] 如何使用 TypeScript 编写 AngularJS 的 Controller?
- Bootstrap 响应式实用工具实例详解
- 在Bootstrap的Modal form里面添加PartialView
- 30分钟快速掌握Bootstrap
- 完成命令时bash可以省略备份文件吗?
- scala – Slick 3.0插入然后获取自动递增值
- SegmentFault D-Day 2016「天津站: 前端场」~ vue干货
- 什么是fn *和Clojure bootstrap如何?