Service là đối tượng dùng chung (như $http, $timeout, $interval) được AngularJS cung cấp cho controller. Bài này đọc dữ liệu JSON từ máy chủ bằng $http và viết service riêng.
Bạn sẽ học được
- Hiểu service và dependency injection
- Gọi $http.get, $http.post
- Dùng $timeout, $interval
- Tạo service riêng
$http
app.controller("ndCtrl", function ($scope, $http) {
$scope.dangTai = true;
$http.get("https://jsonplaceholder.typicode.com/users")
.then(function (res) { $scope.ds = res.data; })
.catch(function (err) { $scope.loi = "Lỗi " + err.status; })
.finally(function () { $scope.dangTai = false; });
});
<p ng-show="dangTai">Đang tải...</p>
<tr ng-repeat="u in ds"><td>{{ u.name }}</td><td>{{ u.email }}</td></tr>$timeout và $interval
app.controller("dongHoCtrl", function ($scope, $interval) {
$scope.gio = new Date();
$interval(function () { $scope.gio = new Date(); }, 1000);
});
<h2>{{ gio | date:"HH:mm:ss" }}</h2>Dùng $timeout, $interval thay cho setTimeout, setInterval để giao diện tự cập nhật.
Service riêng
app.service("tienIch", function () {
this.tongDiem = function (ds) {
return ds.reduce(function (s, x) { return s + x.diem; }, 0);
};
});
app.controller("svCtrl", function ($scope, tienIch) {
$scope.tong = tienIch.tongDiem($scope.ds);
});Lưu ý
Đọc tệp JSON trên máy (file://) bằng $http sẽ bị trình duyệt chặn; hãy chạy trang qua máy chủ web như XAMPP hoặc Live Server.
Thực hành
- Hiển thị bảng người dùng lấy từ API.
- Làm đồng hồ chạy bằng $interval.
- Đọc tệp sinhvien.json trong htdocs và hiển thị.
Tóm tắt bài học
- Service được tiêm vào controller qua tham số.
- $http gọi API, trả về promise.
- app.service tạo service dùng chung.

