AngularJS: Service trong AngularJS

Các khóa học qua video:
Python SQL Server PHP C# Lập trình C Java HTML5-CSS3-JavaScript
Học trên YouTube <76K/tháng. Đăng ký Hội viên
Viết nhanh hơn - Học tốt hơn
Giải phóng thời gian, khai phóng năng lực

Trong AngularJS ta có thể tự tạo service hoặc sử dụng các service sẵn có.

Service là gì?

Trong AngularJS, một service là một function hoặc một đối tượng sẵn có và được giới hạn trong ứng dụng AngularJS của bạn.

AngularJS có khoảng 30 service được tích hợp sẵn, một trong số chúng là service $location.

Service $location có các phương thức trả về thông tin về vị trí của trang web hiện thời.

Ví dụ:

Sử dụng service $location trong một controller:

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>

<div ng-app="myApp" ng-controller="myCtrl">
<p>The url of this page is:</p>
<h3>{{myUrl}}</h3>
</div>

<p>This example uses the built-in $location service to get the absolute url of the page.</p>

<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $location) {
    $scope.myUrl = $location.absUrl();
});
</script>

</body>
</html>

Lưu ý rằng service $location được truyền trong controller dưới dạng đối số. Để sử dụng service trong controller thì nó phải được định nghĩa như một dependency.

Vì sao phải sử dụng Service?

Với nhiều service có vẻ như ta có thể có các đối tượng đã có trong DOM như window.location, nhưng nó có những giới hạn nhất định, ít nhất là đối với ứng dụng AngularJS.

AngularJS liên tục giám sát ứng dụng của bạn và để nó xử lý được các thay đổi và sự kiện đúng cách thì AngularJS muốn bạn sử dụng service $location thay vì đối tượng window.location.

Service $http

Service $http là một trong những service phổ biến nhất trong các ứng dụng AngularJS. Service này sẽ tạo một yêu cầu tới server, và để cho ứng dụng của ta xử lý phản hồi.

Ví dụ

Sử dụng service $http để yêu cầu dữ liệu từ server:

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>

<div ng-app="myApp" ng-controller="myCtrl"> 

<p>Today's welcome message is:</p>

<h1>{{myWelcome}}</h1>

</div>

<p>The $http service requests a page on the server, and the response is set as the value of the "myWelcome" variable.</p>

<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
  $http.get("service-http.html").then(function (response) {
      $scope.myWelcome = response.data;
  });
});
</script>

</body>
</html>

Service $timeout

Service $timeout ứng với hàm window.setTimeout.

Ví dụ:

Hiển thị một thông báo mới sau 2 giây:

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>

<div ng-app="myApp" ng-controller="myCtrl"> 

<p>This header will change after two seconds:</p>

<h1>{{myHeader}}</h1>

</div>

<p>The $timeout service runs a function after a specified number of milliseconds.</p>

<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $timeout) {
  $scope.myHeader = "Hello World!";
  $timeout(function () {
      $scope.myHeader = "How are you today?";
  }, 2000);
});
</script>

</body>
</html>

Service $interval

Service $interval ứng với hàm window.setInterval.

Ví dụ:

Hiển thị thời gian theo từng giây:

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>

<div ng-app="myApp" ng-controller="myCtrl"> 

<p>The time is:</p>

<h1>{{theTime}}</h1>

</div>

<p>The $interval service runs a function every specified millisecond.</p>

<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $interval) {
  $scope.theTime = new Date().toLocaleTimeString();
  $interval(function () {
      $scope.theTime = new Date().toLocaleTimeString();
  }, 1000);
});
</script>

</body>
</html>

Tự tạo Service

Ta có thể tự tạo service của riêng ta như sau:

Tạo một service có tên hexafy:

app.service('hexafy'function() {
    this.myFunc = function (x) {
        return x.toString(16);
    }
});

Để sử dụng service tự tạo thì ta thêm nó như là một dependency khi định nghĩa controller.

Ví dụ:

Sử dụng service tự tạo hexafy ở trên để chuyển số thành số hệ 16 (hexa):

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">

<p>The hexadecimal value of 255 is:</p>

<h1>{{hex}}</h1>

</div>

<p>A custom service with a method that converts a given number into a hexadecimal number.</p>

<script>
var app = angular.module('myApp', []);

app.service('hexafy', function() {
    this.myFunc = function (x) {
        return x.toString(16);
    }
});
app.controller('myCtrl', function($scope, hexafy) {
  $scope.hex = hexafy.myFunc(255);
});
</script>

</body>
</html>

Sử dụng Service tự tạo trong Filter

Một khi service đã kết nối tới ứng dụng của bạn thì bạn có thể sử dụng nó trong bất kỳ controller, chỉ thị, filter nào kể cả là bên trong các service khác.

Để sử dụng service bên trong filter thì ta thêm nó như là một dependency khi định nghĩa filter.

Ví dụ:

Service hexafy được sử dụng trong filter myFormat:

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>

<div ng-app="myApp">
Convert the number 255, using a custom made service inside a custom made filter:

<h1>{{255 | myFormat}}</h1>

</div>

<script>
var app = angular.module('myApp', []);
app.service('hexafy', function() {
    this.myFunc = function (x) {
        return x.toString(16);
    }
});
app.filter('myFormat',['hexafy', function(hexafy) {
    return function(x) {
        return hexafy.myFunc(x);
    };
}]);

</script>

</body>
</html>

Sau đó bạn cũng có thể sử dụng filter khi hiển thị các giá trị của một đối tượng hoặc một mảng.

Ví dụ:

Tạo một service có tên hexafy:

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>

<div ng-app="myApp" ng-controller="myCtrl">
<p>Use a filter when displaying the array [255, 251, 200]:</p>

<ul>
  <li ng-repeat="x in counts">{{x | myFormat}}</li>
</ul>

<p>This filter uses a service that converts numbers into hexadecimal values.</p>
</div>

<script>
var app = angular.module('myApp', []);
app.service('hexafy', function() {
    this.myFunc = function (x) {
        return x.toString(16);
    }
});
app.filter('myFormat',['hexafy', function(hexafy) {
    return function(x) {
        return hexafy.myFunc(x);
    };
}]);
app.controller('myCtrl', function($scope) {
    $scope.counts = [255, 251, 200];
});
</script>

</body>
</html>
» Tiếp: HTTP trong AngularJS AJAX
« Trước: Filter trong AngularJS
Các khóa học qua video:
Python SQL Server PHP C# Lập trình C Java HTML5-CSS3-JavaScript
Học trên YouTube <76K/tháng. Đăng ký Hội viên
Viết nhanh hơn - Học tốt hơn
Giải phóng thời gian, khai phóng năng lực
Copied !!!