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
ヘッダー情報を取得するために使用する関数。.status
HTTPステータスを定義する番号。.statusText
HTTPステータスを定義する文字列。
例
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オブジェクトを確認するには、ここをクリックしてください。
例
ディレクティブは、配列をループするの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データを使用してスコープ内にプロパティを作成します。