AngularJS AJAX- $ http


$ httpは、リモートサーバーからデータを読み取るためのAngularJSサービスです。


AngularJS $ http

AngularJS$httpサービスはサーバーにリクエストを送信し、レスポンスを返します。

サーバーに簡単なリクエストを行い、結果をヘッダーに表示します。

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

<p>Today's welcome message is:</p>
<h1>{{myWelcome}}</h1>

</div>

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

メソッド

上記の例.getでは、サービスのメソッドを使用してい$http ます。

.getメソッドは、$ httpサービスのショートカットメソッドです。いくつかのショートカット方法があります。

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

上記のメソッドはすべて、$ httpサービスを呼び出すためのショートカットです。

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
  $http({
    method : "GET",
      url : "welcome.htm"
  }).then(function mySuccess(response) {
    $scope.myWelcome = response.data;
  }, function myError(response) {
    $scope.myWelcome = response.statusText;
  });
});

上記の例では、オブジェクトを引数として$ httpサービスを実行しています。オブジェクトは、HTTPメソッド、URL、成功時に何をするか、失敗時に何をするかを指定しています。



プロパティ

サーバーからの応答は、次のプロパティを持つオブジェクトです。

  • .configリクエストの生成に使用されるオブジェクト。
  • .dataサーバーからの応答を運ぶ文字列またはオブジェクト。
  • .headersヘッダー情報を取得するために使用する関数。
  • .statusHTTPステータスを定義する番号。
  • .statusTextHTTPステータスを定義する文字列。

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
  $http.get("welcome.htm")
  .then(function(response) {
    $scope.content = response.data;
    $scope.statuscode = response.status;
    $scope.statustext = response.statusText;
  });
});

.thenエラーを処理するには、メソッドにもう1つの関数を追加します。

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
  $http.get("wrongfilename.htm")
  .then(function(response) {
    // First function handles success
    $scope.content = response.data;
  }, function(response) {
    // Second function handles error
    $scope.content = "Something went wrong";
  });
});

JSON

応答から取得するデータは、JSON形式であることが期待されます。

JSONはデータを転送するための優れた方法であり、AngularJSやその他のJavaScript内で簡単に使用できます。

例:サーバーには、15人の顧客を含むJSONオブジェクトを返すファイルがあり、すべてが。という配列でラップされていrecordsます。

JSONオブジェクトを確認するには、ここをクリックしてください。

××

Customers.php

"<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"></head><body><p>{\n\"records\":[\n{\"Name\":\"Alfreds Futterkiste\",\"City\":\"Berlin\",\"Country\":\"Germany\"},\n{\"Name\":\"Ana Trujillo Emparedados y helados\",\"City\":\"México D.F.\",\"Country\":\"Mexico\"},\n{\"Name\":\"Antonio Moreno Taquería\",\"City\":\"México D.F.\",\"Country\":\"Mexico\"},\n{\"Name\":\"Around the Horn\",\"City\":\"London\",\"Country\":\"UK\"},\n{\"Name\":\"B's Beverages\",\"City\":\"London\",\"Country\":\"UK\"},\n{\"Name\":\"Berglunds snabbköp\",\"City\":\"Luleå\",\"Country\":\"Sweden\"},\n{\"Name\":\"Blauer See Delikatessen\",\"City\":\"Mannheim\",\"Country\":\"Germany\"},\n{\"Name\":\"Blondel père et fils\",\"City\":\"Strasbourg\",\"Country\":\"France\"},\n{\"Name\":\"Bólido Comidas preparadas\",\"City\":\"Madrid\",\"Country\":\"Spain\"},\n{\"Name\":\"Bon app'\",\"City\":\"Marseille\",\"Country\":\"France\"},\n{\"Name\":\"Bottom-Dollar Marketse\",\"City\":\"Tsawassen\",\"Country\":\"Canada\"},\n{\"Name\":\"Cactus Comidas para llevar\",\"City\":\"Buenos Aires\",\"Country\":\"Argentina\"},\n{\"Name\":\"Centro comercial Moctezuma\",\"City\":\"México D.F.\",\"Country\":\"Mexico\"},\n{\"Name\":\"Chop-suey Chinese\",\"City\":\"Bern\",\"Country\":\"Switzerland\"},\n{\"Name\":\"Comércio Mineiro\",\"City\":\"São Paulo\",\"Country\":\"Brazil\"}\n]\n} </p></body></html>\n<script>\n    function gtElInit() {\n        var lib = new google.translate.TranslateService();\n        lib.translatePage('', 'ja', function() {});\n    }\n</script>\n<script src=\"https://translate.google.com/translate_a/element.js?cb=gtElInit&amp;client=wt&amp;hl=ja&amp;te=pod\" type=\"text/javascript\"></script>\n\n\n</html>"

ディレクティブは、配列をループするのng-repeatに最適です。

<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("customers.php").then(function(response) {
    $scope.myData = response.data.records;
  });
});
</script>

アプリケーションの説明:

アプリケーションは、 and オブジェクトを使用してcustomersCtrlコントローラーを 定義します。$scope$http

$http外部データを要求するためXMLHttpRequestオブジェクトです。

$http.get()https://www.w3schools.com/angular/customers.phpから JSONデータを読み取ります

成功すると、コントローラーはmyDataサーバーからのJSONデータを使用してスコープ内にプロパティを作成します。