鍍金池/ 教程/ HTML/ REST 和定制服務(wù) - REST and Custom Services
完結(jié)篇 - The End
迭代器 - Filtering Repeaters
過(guò)濾器 - Filters
靜態(tài)模版 - Static Template
引導(dǎo)程序 - Bootstrapping
路由與多視圖 - Routing Multiple Views
動(dòng)畫(huà)操作 - Applying Animations
導(dǎo)言
雙向綁定 - Two-way Data Binding
更多模版 - More Templating
連接與圖片模版- Templating Links Images
事件處理器 - Event Handlers
AngularJS 模版 - Angular Templates
XHR 和依賴(lài)注入 - XHRs Dependency Injection
REST 和定制服務(wù) - REST and Custom Services

REST 和定制服務(wù) - REST and Custom Services

在這一步中,我們會(huì)改進(jìn)我們APP獲取數(shù)據(jù)的方式。

請(qǐng)重置工作目錄:

    git checkout -f step-11

對(duì)我們應(yīng)用所做的最后一個(gè)改進(jìn)就是定義一個(gè)代表 [RESTful][http://en.wikipedia.org/wiki/Representational_State_Transfer] 客戶(hù)端的定制服務(wù)。有了這個(gè)客戶(hù)端我們可以用一種更簡(jiǎn)單的方式來(lái)發(fā)送XHR請(qǐng)求,而不用去關(guān)心更底層的 $http 服務(wù)(API、HTTP方法和URL)。

步驟9和步驟10之間最重要的不同在下面列出。你可以在 [GitHub][https://github.com/angular/angular-phonecat/compare/step-10...step-11] 里看到完整的差別。

模板

定制的服務(wù)被定義在app/js/services,所以我們需要在布局模板中引入這個(gè)文件。另外,我們也要加載angularjs-resource.js這個(gè)文件,它包含了ngResource模塊以及其中的$resource服務(wù),我們一會(huì)就會(huì)用到它們:

app/index.html

    ...
      <script src="js/services.js"></script>
      <script src="lib/angular/angular-resource.js"></script>
    ...

服務(wù)

app/js/services.js

    angular.module('phonecatServices', ['ngResource']).
        factory('Phone', function($resource){
          return $resource('phones/:phoneId.json', {}, {
            query: {method:'GET', params:{phoneId:'phones'}, isArray:true}
          });
        });

我們使用模塊API通過(guò)一個(gè)工廠方法注冊(cè)了一個(gè)定制服務(wù)。我們傳入服務(wù)的名字Phone和工廠函數(shù)。工廠函數(shù)和控制器構(gòu)造函數(shù)差不多,它們都通過(guò)函數(shù)參數(shù)聲明依賴(lài)服務(wù)。Phone服務(wù)聲明了它依賴(lài)于$resource服務(wù)。

[$resource][ngResource.$resource]服務(wù)使得用短短的幾行代碼就可以創(chuàng)建一個(gè) [RESTful][http://en.wikipedia.org/wiki/Representational_State_Transfer] 客戶(hù)端。我們的應(yīng)用使用這個(gè)客戶(hù)端來(lái)代替底層的[$http][ng.$http]服務(wù)。

app/js/app.js

    ...
    angular.module('phonecat', ['phonecatFilters', 'phonecatServices']).
    ...

我們需要把phonecatServices添加到phonecat的依賴(lài)數(shù)組里。

控制器

通過(guò)重構(gòu)掉底層的[$http][ng.$http]服務(wù),把它放在一個(gè)新的服務(wù)Phone中,我們可以大大簡(jiǎn)化子控制器(PhoneListCtrlPhoneDetailCtrl)。AngularJS的[$resource][ngResource.$resource]相比于$http更加適合于與RESTful數(shù)據(jù)源交互。而且現(xiàn)在我們更容易理解控制器這些代碼在干什么了。

app/js/controllers.js

    ...

    function PhoneListCtrl($scope, Phone) {
      $scope.phones = Phone.query();
      $scope.orderProp = 'age';
    }

    //PhoneListCtrl.$inject = ['$scope', 'Phone'];

    function PhoneDetailCtrl($scope, $routeParams, Phone) {
      $scope.phone = Phone.get({phoneId: $routeParams.phoneId}, function(phone) {
        $scope.mainImageUrl = phone.images[0];
      });

      $scope.setImage = function(imageUrl) {
        $scope.mainImageUrl = imageUrl;
      }
    }

    //PhoneDetailCtrl.$inject = ['$scope', '$routeParams', 'Phone'];

注意到,在`PhoneListCtrl`里我們把:

    $http.get('phones/phones.json').success(function(data) {
      $scope.phones = data;
    });

換成了:

    $scope.phones = Phone.query();

我們通過(guò)這條簡(jiǎn)單的語(yǔ)句來(lái)查詢(xún)所有的手機(jī)。

另一個(gè)非常需要注意的是,在上面的代碼里面,當(dāng)調(diào)用Phone服務(wù)的方法是我們并沒(méi)有傳遞任何回調(diào)函數(shù)。盡管這看起來(lái)結(jié)果是同步返回的,其實(shí)根本就不是。被同步返回的是一個(gè)“future”——一個(gè)對(duì)象,當(dāng)XHR相應(yīng)返回的時(shí)候會(huì)填充進(jìn)數(shù)據(jù)。鑒于AngularJS的數(shù)據(jù)綁定,我們可以使用future并且把它綁定到我們的模板上。然后,當(dāng)數(shù)據(jù)到達(dá)時(shí),我們的視圖會(huì)自動(dòng)更新。

有的時(shí)候,單單依賴(lài)future對(duì)象和數(shù)據(jù)綁定不足以滿(mǎn)足我們的需求,所以在這些情況下,我們需要添加一個(gè)回調(diào)函數(shù)來(lái)處理服務(wù)器的響應(yīng)。PhoneDetailCtrl控制器通過(guò)在一個(gè)回調(diào)函數(shù)中設(shè)置mainImageUrl就是一個(gè)解釋。

測(cè)試

修改我們的單元測(cè)試來(lái)驗(yàn)證我們新的服務(wù)會(huì)發(fā)起HTTP請(qǐng)求并且按照預(yù)期地處理它們。測(cè)試同時(shí)也檢查了我們的控制器是否與服務(wù)正確協(xié)作。

[$resource][ngResource.$resource]服務(wù)通過(guò)添加更新和刪除資源的方法來(lái)增強(qiáng)響應(yīng)得到的對(duì)象。如果我們打算使用toEqual匹配器,我們的測(cè)試會(huì)失敗,因?yàn)闇y(cè)試值并不會(huì)和響應(yīng)完全等同。為了解決這個(gè)問(wèn)題,我們需要使用一個(gè)最近定義的toEqualData[Jasmine匹配器][]。當(dāng)toEqualData匹配器比較兩個(gè)對(duì)象的時(shí)候,它只考慮對(duì)象的屬性而忽略掉所有的方法。

test/unit/controllersSpec.js:

    describe('PhoneCat controllers', function() {

      beforeEach(function(){
        this.addMatchers({
          toEqualData: function(expected) {
            return angular.equals(this.actual, expected);
          }
        });
      });

     beforeEach(module('phonecatServices'));

      describe('PhoneListCtrl', function(){
        var scope, ctrl, $httpBackend;

        beforeEach(inject(function(_$httpBackend_, $rootScope, $controller) {
          $httpBackend = _$httpBackend_;
          $httpBackend.expectGET('phones/phones.json').
              respond([{name: 'Nexus S'}, {name: 'Motorola DROID'}]);

          scope = $rootScope.$new();
          ctrl = $controller(PhoneListCtrl, {$scope: scope});
        }));

        it('should create "phones" model with 2 phones fetched from xhr', function() {
          expect(scope.phones).toEqual([]);
          $httpBackend.flush();

          expect(scope.phones).toEqualData(
              [{name: 'Nexus S'}, {name: 'Motorola DROID'}]);
        });

        it('should set the default value of orderProp model', function() {
          expect(scope.orderProp).toBe('age');
        });
      });

      describe('PhoneDetailCtrl', function(){
        var scope, $httpBackend, ctrl,
            xyzPhoneData = function() {
              return {
                name: 'phone xyz',
                images: ['image/url1.png', 'image/url2.png']
              }
            };

        beforeEach(inject(function(_$httpBackend_, $rootScope, $routeParams, $controller) {
          $httpBackend = _$httpBackend_;
          $httpBackend.expectGET('phones/xyz.json').respond(xyzPhoneData());

          $routeParams.phoneId = 'xyz';
          scope = $rootScope.$new();
          ctrl = $controller(PhoneDetailCtrl, {$scope: scope});
        }));

        it('should fetch phone detail', function() {
          expect(scope.phone).toEqualData({});
          $httpBackend.flush();

          expect(scope.phone).toEqualData(xyzPhoneData());
        });
      });
    });

執(zhí)行./scripts/test.sh運(yùn)行測(cè)試,你應(yīng)該會(huì)看到如下的輸出:

    Chrome: Runner reset.
    ....
    Total 4 tests (Passed: 4; Fails: 0; Errors: 0) (3.00 ms)
      Chrome 19.0.1084.36 Mac OS: Run 4 tests (Passed: 4; Fails: 0; Errors 0) (3.00 ms)

總結(jié)

現(xiàn)在我們已經(jīng)看到了如何建立一個(gè)定制服務(wù)REST,我們已經(jīng)準(zhǔn)備好了動(dòng)畫(huà)操作(最后一步!),以了解如何改善這個(gè)應(yīng)用程序的動(dòng)畫(huà)。

上一篇:導(dǎo)言