使用Angular Resources 封装Rest API

使用$http直接访问接口

$http是angular提供的http调用的基础服务。

基本用法为:

$http(config);

config对象主要包含对诸如请求地址url,请求方法method,查询参数参数param.以及post对应的data等。 对于某些特定的http服务如oauth等需要在http头信息中包含一些特定的数据,这些都可以在config中进行配置,配置详情请参考官方文档。

除此之外$http还提供了一些快捷方法如下所示:

$http.get(url, [config])
$http.head(url, [config])
$http.post(url, data, [config])
$http.put(url, data, [config])
$http.delete(url, [config])
$http.jsonp(url, [config])

示例:

$http({method: 'GET', url: '/someUrl'}).
    success(function(data, status, headers, config) {
      // this callback will be called asynchronously
      // when the response is available
    }).
    error(function(data, status, headers, config) {
      // called asynchronously if an error occurs
      // or server returns response with an error status.
    });

除此之外$http还提供了请求拦截机制 Interceptors 可以对api请求进行统一的错误处理等功能。


$http结合Factory封装访问接口

factory 是 Angular 中 $provide 注册组件的方法之一(常用的其他方法还包括provider, value, service),这里可以简单理解为一个对象工厂,通过注册一个factory我们可以将后端程序提供的API接口进行统一的封装。

示例:

定义工厂:

angular.module('someApp')
    .factory('FactoryName', ['$http', function(){
        return {
            get: function(){ return $http.get('someUrl'); },
            query: function(){ return $http.get('someUrl'); },
            update: function(){ return $http.put('someUrl'); },
            delete: function(){ return $http.del('someUrl'); },
            otherAction: function(){ return $http.del('someUrl'); }
        }
    }]);

在controllrt中使用:

angular.module('someApp')
    .controller('MainCtrl', function ($scope, FactoryName) {
            FactoryName.query().success().error();
        });

使用 $resource 封装Rest接口

如上所示 $http 基本可以满足对API接口调用的所有需求,$http 提供的是一个非常低级的实现,但是具有非常好的灵活性。对于REST类型的API接口还提供了一个独立的可选模块 ngResource。 该模块容许我们定义一个资源描述对象来代表响应的REST资源,通过面向对象的方式来操作响应的REST API接口。

使用 $resource 服务需要导入单独的 angular-reources.js 文件

用法:

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

resource 描述资源对象主要包含:资源URL地址 (url);请求的方法 (method);默认的参数,以及附属的其他方法,返回值是数组或者对象等信息(isArray)。

示例:

var SomeResources = $resource('/api/resourfes/:id', null, {
   action1: {
     method: 'GET',
     url: 'someOtherUrl',
     isArray: true  
   }
});

如上所定义的 SomeResources 对象包含 resource 提供的默认方法 get(), save(), query(), remove(), delete() 等默认方法,以及自定义的 action1 方法。

在调用过程中的映射关系如下:($resources并未提供默认的put方法)

资源函数方法地址返回结果
SomeResources.get({id: id})GEThttp /api/resources/:idJSON对象
SomeResources.save({}, res)POSThttp POST api/resources data=dataJSON对象
SomeResources.query()GEThttp /api/resourcesJSON数组
SomeResources.remove({id:id})DELETEhttp DELETE /api/resources/:idJSON对象

示例:

angular.module('someApp')
    .factory('FactoryName', ['$resource', function($resource){
       return $resource('someUrl', null, {
           action1: {
             method: 'GET',
             url: 'someOtherUrl',
             isArray: true  
           }
       });
    }]);

原文链接

https://github.com/yunlzheng/workspace/wiki/%E4%BD%BF%E7%94%A8Angular-Resources-%E5%B0%81%E8%A3%85Rest-API

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值