-1

Cách sử dụng service trong AngularJs

1, Giới thiệu

Service là một component quan trọng trong cấu trúc của một AngularJs application. Services là các javascript functions mà đáp ứng một nhiệm vụ xác định nào đó. Nhờ việc phân chia các tasks vào các services mà các angular applications duy trì được cấu trúc 'Separation of Concerns', và hơn thế nữa services cũng làm cho angular application dễ maintainable và testable hơn. Các controllers, filters có thể gọi các services dùng phương pháp dependency injection (DI).

angular-service2.jpg

AngularJs có 2 loại services là built-in services và custom services. Trong bài viết này, tôi sẽ giới thiệu đến các bạn cách sử dụng một số built-in services phổ biến trong AngularJs và các cách để tạo một custom services.

2, Cách sử dụng Services trong AngularJs

2.1, Built-in Services

AngularJs cung cấp khoảng 30 built-in services. Mỗi service lại đáp ứng một nhiệm vụ nhất định.

2.1.1, $http service

$http là một service phổ biến trong AngularJs dùng để tạo các ajax request lên server. Cách dùng:

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
    $http.get("welcome.htm")
    .then(function(response) {
        $scope.myWelcome = response.data;
    }, function(error){
      console.log(error);
    };
});

Trong ví dụ trên bạn có thể thấy tôi đã dùng phương pháp DI để đưa $http service vào trong controller hiện tại. Tôi đã sử dụng $http để tạo một GET request tới welcome.htm của server. Kết quả của $http GET là một promise object vì thế chúng ta có thể sử dụng các callback function trên nó, ở đây tôi sử dụng then function để xử lý các trường hợp request thành công và không thành công. Bạn có thể sử dụng các http methods khác để thực hiện các thao tác xác định với dữ liệu trên server ví dụ: POST, PUT, DELETE.

2.1.2, $location

$location một service mà AngularJs cung cấp dùng để parse url trên address bar hoặc tạo một url mới cho application.
Cách dùng:

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $location) {
    // dùng $location để lấy thông tin của url
    var absUrl = $location.absUrl(); //=>"http://example.com/#/some/path?foo=bar&baz=xoxo"
    var url = $location.url() //=> '/some/path?foo=bar&baz=xoxo'
    var path = $location.path() //=> 'some/path'
    var search = $location.search() => '{foo: 'bar', baz: 'xoxo'}'
});

Như bạn thấy ở trên $location có thể được dùng để get thông tin từ url hiện tại hoặc thay đổi các thành phần trên url.

2.1.3, $filter

filters là các thành phần phổ biến được sử dụng trên các view để format hoặc lọc dữ liệu trước khi display với các function như: currency, filter, orderBy, date, limitTo, …
Nhưng đôi khi chúng ta cũng muốn sử dụng các filter này trong angular controller. Để thực hiện điều này chúng ta cần inject $filter service vào trong controller
Cách dùng:

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $filter) {
    var students = [
      {id: 1, name: 'bob', age: 20, gender: 'male'},
      {id: 2, name: 'Alice', age: 25, gender: 'female'},
      {id: 3, name: 'Emma', age: 18, gender: 'female'},
    $scope.studentsFilterdByGender = $filter.filter(students, {gender: 'female'});
    ];
});

Trong ví dụ trên, các bạn có thể thấy tôi đã sử dụng $filter service để filter mảng student theo giới tính là nữ.

Ngoài các services kể trên, AngularJs còn cung cấp nhiều built-in services hữu ích khác. Bạn có thể tham khảo thêm tại: https://docs.angularjs.org/api/

2.2, Custom services

Khi mà các built-in services chưa đáp ứng được yêu cầu hiện tại của bạn, bạn hoàn toàn có thể tạo custom services của riêng bạn. Có 3 cách để tạo custom services phổ biến là:

  • Module.factory
  • Module.service
  • Module.provider

Tôi sẽ lần lượt giới thiệu với các bạn 3 cách tạo custom services này.

2.2.1, Dùng Factory method

Cách đơn giản nhất để tạo một custom service là dùng Module.factory method.
Cách dùng:

angular.module('customService', [])
  .factory('logService', function() {
    var messageCount = 0;
    return {
      log: function(msg) {
        console.log('LOG' + messageCount++ + msg);
      };
    };
  });

Ở ví dụ trên, bạn có thể thấy tôi đã gọi factory method trên module object. Method này chứa 2 tham số, tham số thứ nhất là tên của service, tham số thứ 2 là một factory function nó trả về một object mà định nghĩa một log function. Object này sẽ được dùng bất cứ khi nào logService được request.

Sau khi đã tạo service chúng ta có thể sử dụng nó cho application bình thường như các buit-in service khác.

angular.module('customService')
  .controller('myCtrl', function($scope, customService) {
    //more code go here....
  });

2.2.2, Dùng Service method

Dùng service method, chúng ta sẽ định nghĩa một service và gán method tới nó.

angular.module('customService', []).service('Calcservice', function(MathService) {
  this.square = function(a) {
    return MathService.multiply(a, a);
  };
});

Việc sử dụng customService vừa định nghĩa ở trên cũng giống như sử dụng một buit-in service thông thường.

2.2.3, Dùng Provider method

Module.provider method cho phép chúng ta có nhiều điều khiển hơn khi tạo cũng như cấu hình một service.

Cách dùng:

angular.module('myApp', []).provider('logService', function() {
  return {
    $get: function() {
      return {
        messageCount: 0,
        log: function(msg) {
          console.log('LOG' + this.messageCount++ + msg);
        }
      };
    }
  }
});

Tham số tới provider method là tên service và một factory function. Factory function trả về một provider object, nó định nghĩa một method được gọi là $get, nó được yêu cầu để trả về một object service. Khi service được yêu cầu, AngularJs gọi factory function để get provider object và sau đó gọi $get method để get service object. Service được tạo bởi provider function cũng giống như các built-in service thông thường.

3, Kết luận

Service là một component quan trọng trong AngularJs. Sử dụng Service cho các application giúp code có khả năng sử dụng lại cao, dễ maintain, dễ test, nâng cao tính separation cho application. Angular là một framework cũng rất mềm dẻo, nó cung cấp cho chúng ta rất nhiều built-in services và nhiều cách khác nhau để tạo custom services việc lựa chọn sử dụng service nào, cách nào để tạo service phụ thuộc vào sở thích, thói quen, và đặc thù project hiện tại của bạn.
Cảm ơn các bạn đã quan tâm đến bài viết của tôi, hẹn gặp lại ở các bài viết sau.

Tài liệu tham khảo
https://docs.angularjs.org/guide/services
https://www.tutorialspoint.com/angularjs/angularjs_services.htm
http://www.w3schools.com/angular/angular_services.asp


All rights reserved

Viblo
Hãy đăng ký một tài khoản Viblo để nhận được nhiều bài viết thú vị hơn.
Đăng kí