AngularJS: HTTP trong AngularJS AJAX

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

$http là một service AngularJS dùng để đọc dữ liệu từ máy chủ từ xa (remote).

Service $http

Service $http tạo một yêu cầu (request) tới server, và trả về một response.

<!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-demo.html").then(function (response) {
      $scope.myWelcome = response.data;
  });
});
</script>

</body>
</html>

 

Các phương thức của service $http

Ví dụ trên sử dụng phương thức .get của service $http.

Phương thức .get là một phương thức thu gọn của service $http. Có một số phương thức thu gọn như sau:

  • .delete()
  • .get()
  • .head()
  • .jsonp()
  • .patch()
  • .post()
  • .put()

Ví dụ trên thực thi service $http với một đối tượng dưới dạng một đối số. Đối tượng sẽ xác định phương thức HTTP, url, phải làm gì khi xử lý thành công, và phải làm gì khi gặp lỗi. Dưới đây là ví dụ:

<!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({
    method : "GET",
    url : "service-http-demo.html"
  }).then(function mySuccess(response) {
      $scope.myWelcome = response.data;
    }, function myError(response) {
      $scope.myWelcome = response.statusText;
  });
});
</script>

</body>
</html>

Các thuộc tính

Phản hồi từ server sẽ là một đối tượng gồm những thuộc tính sau:

  • .config đối tượng sử dụng để tạo request.
  • .data là một chuỗi hoặc một đối tượng chứa phản hồi từ server.
  • .headers là một hàm dùng để lấy thông tin header.
  • .status một số xác định trạng thái của HTTP.
  • .statusText một chuỗi xác định trạng thái HTTP.

Ví dụ:

<!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>Data : {{content}}</p>
<p>Status : {{statuscode}}</p>
<p>StatusText : {{statustext}}</p>

</div>

<p>The response object has many properties. This example demonstrate the value of the data, status, and statusText properties.</p>

<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
  $http.get("service-http-demo.html1")
  .then(function(response) {
      $scope.content = response.data;
      $scope.statuscode = response.status;
      $scope.statustext = response.statusText;            
  });
});
</script>

</body>
</html>

Để xử lý lỗi bạn thêm một hoặc nhiều hàm tới phương thức .then.

Ví dụ:

<!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"> 

<h1>{{content}}</h1>

</div>

<p>The $http service executes different functions on success and failure.</p>

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

</body>
</html>

JSON

Dữ liệu bạn lấy từ phản hồi (response) được định dạng là JSON.

JSON là một cách rất hay để truyền dữ liệu, và nó dễ sử dụng trong AngularJS cũng như trong JavaScript.

Ví dụ: Trên server ta có một file trả về một đối tượng JSON có chứa 15 khách hàng, tất cả đều được gộp vào một mảng gọi là records.

<!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="customersCtrl"> 

<ul>
  <li ng-repeat="x in myData">
    {{ x.Name + ', ' + x.Country }}
  </li>
</ul>

</div>

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

</body>
</html>

File service-http-customers.php có nội dung sau:

{
  "records": [
    {
      "Name": "Alfreds Futterkiste",
      "City": "Berlin",
      "Country": "Germany"
    },
    {
      "Name": "Ana Trujillo Emparedados y helados",
      "City": "México D.F.",
      "Country": "Mexico"
    },
    {
      "Name": "Antonio Moreno Taquería",
      "City": "México D.F.",
      "Country": "Mexico"
    },
    {
      "Name": "Around the Horn",
      "City": "London",
      "Country": "UK"
    },
    {
      "Name": "B's Beverages",
      "City": "London",
      "Country": "UK"
    },
    {
      "Name": "Berglunds snabbköp",
      "City": "Luleå",
      "Country": "Sweden"
    },
    {
      "Name": "Blauer See Delikatessen",
      "City": "Mannheim",
      "Country": "Germany"
    },
    {
      "Name": "Blondel père et fils",
      "City": "Strasbourg",
      "Country": "France"
    },
    {
      "Name": "Bólido Comidas preparadas",
      "City": "Madrid",
      "Country": "Spain"
    },
    {
      "Name": "Bon app'",
      "City": "Marseille",
      "Country": "France"
    },
    {
      "Name": "Bottom-Dollar Marketse",
      "City": "Tsawassen",
      "Country": "Canada"
    },
    {
      "Name": "Cactus Comidas para llevar",
      "City": "Buenos Aires",
      "Country": "Argentina"
    },
    {
      "Name": "Centro comercial Moctezuma",
      "City": "México D.F.",
      "Country": "Mexico"
    },
    {
      "Name": "Chop-suey Chinese",
      "City": "Bern",
      "Country": "Switzerland"
    },
    {
      "Name": "Comércio Mineiro",
      "City": "São Paulo",
      "Country": "Brazil"
    }
  ]
}

Giải thích:

Ứng dụng định nghĩa controller customersCtrl, với một $scope và một $http.

$http là một đối tượng XMLHttpRequest dùng để request dữ liệu ngoài.

$http.get() sẽ đọc dữ liệu JSON từ file service-http-customers.php.

Khi thành công thì controller sẽ tạo một thuộc tính tên myData trong scope, với dữ liệu JSON từ server.

» Tiếp: Table trong AngularJS
« Trước: 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
Copied !!!