[译]AngularJS Services 获取后端数据

原文:ANGULARJS SERVICES – FETCHING SERVER DATA

$http是AngularJS内置的服务,能帮助我们完成从服务端获数据。简单的用法就是在你需要数据的时候,发起$http请求,使用返回的数据。这个样做是能工作,但是当你的应用越来越复杂的时候,你会发现你在不断的重复的写这个http请求的代码。为了避免这种事情的发生,我们应该使用AngularJS的service。

通过AngularJS service有多种不同的办法可以解决问题,这里我介绍两种方法来解决$http可重用的问题。

  1. 一个service来管理应用中所有的http请求
  2. 一个model一个service


简单使用示例

让我们假设你有个网上商店,你有3个models - products, categories 和 users。现在你想为每个model建立增删改查的操作。下面列出两种不同的方法来实现这个service。


多个Endpoint公用的sercice
angular.module('angular-shop-http').service('httpService', function($rootScope, $http, $q) {
    var httpService = {};
 
    httpService.get = function(id, endpoint) {
        var deferred = $q.defer();
        var url = 'www.panda-os.com/' + endPoint;
        var queryParams = {};
        if (typeof id != 'undefined' && typeof id != null) {
            queryParams = { id: id};
        }
        $http({
            method: 'GET',
            url: url,
            headers: {
                'Content-Type': 'application/json',
            },
            params: queryParams,
            cache: false
        }).
            success(function(data, status, headers, config) {
                deferred.resolve(data);
            }).
            error(function(data, status, headers, config) {
                deferred.reject(data);
            });
 
        return deferred.promise;
    };
 
    return httpService;
 
});

如你所见,我们创建了一个通用的sercie来完成所有的http请求。我们只需要调用httpService.get(),传入我们要请求的Endpoint名字(products, user, categories) ,带上必要的参数就可以了。这里我们只写了get的方法,其实我们应该实现所有剩下的CRUD操作。


一个model一个sercice

-Product Service

angular.module('angular-shop-products').service('productService', function($rootScope, $http, $q) {
    var productService = {};
 
    productService.get = function(id) {
        var deferred = $q.defer();
        var endPoint = "products/";
        var url = 'www.panda-os.com/' + endPoint;
        var queryParams = {};
        if (typeof id != 'undefined' && typeof id != null) {
            queryParams = { id: id};
        }
        $http({
            method: 'GET',
            url: url,
            headers: {
                'Content-Type': 'application/json',
 
            },
            params: queryParams,
            cache: false
        }).
            success(function(data, status, headers, config) {
                deferred.resolve(data);
            }).
            error(function(data, status, headers, config) {
                deferred.reject(data);
            });
 
        return deferred.promise;
    };
 
    return productService;
 
});

-User Service

angular.module('angular-shop-products').service('userService', function($rootScope, $http, $q) {
    var userService = {};
 
    userService.get = function(id) {
        var deferred = $q.defer();
        var endPoint = "user/";
        var url = 'www.panda-os.com/' + endPoint;
        var queryParams = {};
        if (typeof id != 'undefined' && typeof id != null) {
            queryParams = { id: id};
        }
        $http({
            method: 'GET',
            url: url,
            headers: {
                'Content-Type': 'application/json',
 
            },
            params: queryParams,
            cache: false
        }).
            success(function(data, status, headers, config) {
                deferred.resolve(data);
            }).
            error(function(data, status, headers, config) {
                deferred.reject(data);
            });
 
        return deferred.promise;
    };
 
    return userService;
 
});

上面的实例中我们看到,每个model都有一个对应的Endpoint service。每个服务只负责一个model的操作。同样的我只写了get方法,实际开发中应该完成所有剩下的CRUD操作。


更多阅读

AngularJS Service
AngularJS Service – Application Data Management
AngularJS Service – Application Business Logic


翻译收获

上面的代码没有什么难点,这里可以注意下如何使用AngularJS的promise实现简单易用的异步对象


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值