angular-restful

本文介绍如何使用Angular的$resource服务与RESTful接口进行交互,通过一个DEMO展示了创建表单、验证用户名唯一性及GET、PUT、DELETE操作。前端采用Angular、Bootstrap和Font Awesome,后端使用Express和Lodash。详细讲述了$resourceProvider的配置以及如何构建RESTful的factory。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

关于 resource使 http服务。相对于 http, resource对于restful的对接更加方便,这里写了一个demo,有兴趣的可以看一下。

你需要看得懂:
1. expressjs
2. jade
3. angular

demo实现的功能
前端利用angular构建一个From,和一个Table,表单将用户名和密码以及邮箱发送到服务端(本来准备用上mongodb的,怕写的东西太多了,就直接用一个users=[]的集合代替),后端验证用户名唯一后添加进users集合。
而关于get,put,delete功能就在table上操作。

这里我用的是express,关于如何初始化一个express工程,前面的文章里面有写过了,这里就不再说什么了,直接贴上路由文件index.js

var express = require('express');
var _ = require("lodash");
var router = express.Router();

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index');
});

var users=[];
//获取用户列表
router.get("/user",function(req,res){
  res.json(users)
});

//添加新的用户
router.post("/user",function(req,res){
  console.log(req.body.name);
  //查询用户是否存在
  if(!_.find(users,{name:req.body.name})){
    users.push(req.body);
    res.json(req.body)
  }
  else{
    res.json(null)
  }
});
//更新用户信息
router.put("/user",function(req,res){
  users= _.map(users,function(v){
    if(v.name==req.body.name){
      return v = req.body
    }
    return v
  });
  res.json(req.body)
});
//删除用户
router.delete("/user/:name",function(req,res){
   //console.log(req.params);
   users= _.filter(users,function(v){
     return v.name!=req.params.name
   });
  res.json(req.params)
});
module.exports = router;

对于users集合的操作,我这里用的是lodash。

然后是关于前端的代码
为了页面好看点,我这里使用的是bootstrap,以及bootwacth主题,图标方面用的是font-awesome。所以我的layout是这样的

doctype html
html(ng-app="app")
  head
    title= title
    link(href="/paper/bootstrap.min.css" rel="stylesheet")
    link(href="/font-awesome/css/font-awesome.min.css" rel="stylesheet")
    script(src="/jquery/dist/jquery.min.js")
    script(src="/bootstrap/dist/js/bootstrap.min.js")
    script(src="/angular/angular.min.js")
    script(src="/angular/angular-resource.min.js")
  body
    block content

注意resource服务需要单独引入。

接下来就是app.js文
首先为了保证请求的正确性,我们需要配置$resourceProvider的默认设置

            $resourceProvider.defaults.stripTrailingSlashes = false;

然后,让我们看下谷歌官方的api

$resource(url, [paramDefaults], [actions], options);

url就是请求的url地址
paramDefaults的话就是请求的附带参数,举个例子

$resource("/user/:_id",{_id:"123"})
//=   /user/123

action就是我们可以根据这个请求构建不同的请求方式

我这里构建了一个restful的factory,为了方便以后的开发

.factory("restful", function ($resource) {
            var restful = this
            restful.user = $resource("/user/:name", {name: "@id"},
                {
                    getOneUser: {method: "GET"},
                    getUsers: {method: "GET", params: {}, isArray: true},
                    createUser: {method: "POST"},
                    updateUser:{method:"PUT"},
                    delUser:{method:"DELETE"}
                }
            );
            return restful
        })

这里注意一下,加入返回的是集合的话,需要设置isArray为true。补充一下,关于action,我们可用的属性有:

  1. action
  2. method
  3. params
  4. url
  5. isArray
  6. transformRequest
  7. transformResponse
  8. cache
  9. timeout
  10. cancellable
  11. withCredentials
  12. responseType
  13. interceptor

但是本文中 就不多做介绍了,具体每个的作用可以看官方文档。

然后就是controller文件

.controller("restful", function ($scope, restful) {
        //定义一个初始化用户列表   的方法
            var userInit =  function(){
                restful
                    .user
                    .getUsers()
                    .$promise
                    .then(function (res) {
                        console.log(res)
                        $scope.users = res
                    });
            };
            //初始化用户
            userInit();
            //创建一个新的用户
            $scope.login = function (user) {
                restful
                    .user
                    .createUser(user)
                    .$promise
                    .then(function (res) {
                        console.log(res)
                        userInit();
                    })
            };
            //更新用户信息
            $scope.put =function(user){
              console.log(user)
                restful
                    .user
                    .updateUser(user)
                    .$promise
                    .then(function(res){
                        userInit()
                    })
            };
            //删除用户
            $scope.del = function(user){
                restful
                    .user
                    .delUser({name:user.name})
                    .$promise
                    .then(function(res){
                        userInit()
                    })
            }

        })

可以看到,调用这个restful服务调用起来还是很方便的。

最后是关于前端index的代码

extends layout
block content
   .container(ng-controller="restful")
      br
      br
      ng-form.col-md-4(novalidate name="userForm" )
          fieldset
             legend Angular-Express-Restful
             .form-group.has-feedback
                 input.form-control#username(type="text" minLength=4 placeholder="username" ng-model="user.name" required)
                 span.fa.fa-user.form-control-feedback(style="margin-top:10px;")
             .form-group.has-feedback
                 input.form-control#passworl(type="password" minLength=4 placeholder="password" ng-model="user.password" required)
                 span.fa.fa-lock.form-control-feedback(style="margin-top:10px;")
             .form-group.has-feedback
                 input.form-control#email(type="email" placeholder="Email" ng-model="user.email" required)
                 span.fa.fa-envelope.form-control-feedback(style="margin-top:10px;" )
             button.btn.btn-warning(type="submit" ng-disabled="userForm.$invalid" ng-click="login(user)") 提交
      .col-md-8
          table.table.table-default.table-hover
              thead
                tr
                    th #
                    th 用户名
                    th 密码
                    th 邮箱
                    th 修改
                    th 删除
              tbody
                  tr(ng-repeat="user in users" ng-init="user.edit=false;")
                    td {{$index}}
                    td {{user.name}}
                    td
                        input.form-control(ng-model="user.password" ng-show="user.edit")
                        div(ng-show="!user.edit") {{user.password}}
                    td
                        input.form-control(ng-model="user.email" ng-show="user.edit")
                        div(ng-show="!user.edit") {{user.email}}
                    td
                        button.btn.btn-primary(style="padding:2px 5px" ng-click="user.edit=!user.edit;" ng-show="!user.edit")
                            span.fa.fa-edit
                        button.btn.btn-warning(style="padding:2px 5px" ng-click="put(user)" ng-show="user.edit")
                            span.fa.fa-send
                    td
                        button.btn.btn-danger(style="padding:2px 5px" ng-click="del(user)")
                            span.fa.fa-trash
   script(src="/js/app.js")

附上截图
这里写图片描述

完整工程地址https://github.com/zezhipeng/angular-express-restful

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值