[译]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 ```js 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操作。

<br>
####一个model一个sercice
-Product Service
```js
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实现简单易用的异步对象
posted @ 2016-11-21 17:22  CooMark  阅读(1364)  评论(0编辑  收藏  举报