この記事では、Angularjsを使用してHTTP要求をリモートAPIに作成し、JSON応答でビューを更新する方法を示しています。 Angularのサービスとデータのバインディングを活用します
$http
$http.get
および)。
details
related
ngModelOptions
debounce
サービス:$watch
約束:search
:偏向の代わりに約束を使用した最新のエラー処理.then()
プロジェクト構造とコードのハイライト:.success()
およびを含むモデルにバインドされています)と、部分的なビュー(
および)をロードするためのディレクティブが含まれます。
index.html
コアロジックはsearch
、具体的にはng-model
に存在します。 ng-model-options
行は、debounce期間後に検索入力が変更されるたびにng-include
関数が呼び出されることを保証します。 main-info.html
related-results.html
を使用して、2つのAPI呼び出し(1つはメイン映画の詳細、1つは関連する映画用)をOMDB APIに行います。 回答は、
に割り当てられます。 関連する映画のタイトルをクリックし、app.js
モデルを更新します。
MovieController
部分的なビュー($watch('search', fetch)
およびfetch()
)は、Angularのデータバインディングを使用して映画情報を表示します。 fetch()
条件論的ロジック($http.get
)が含まれており、ロード状態と欠落しているポスター画像を処理します。 $scope.details
クリック時に$scope.related
を使用して関連する映画を繰り返し、update()
を呼び出します。
search
main-info.html
related-results.html
記事は、2016-01-17で行われた更新を記録します
main-info.html
ng-if
related-results.html
/ng-repeat
をupdate()
debounceおよび
に置き換えます プロミスハンドリングにを使用するために更新。
壊れたポスター画像を修正します。
setTimeout
コードスニペットの例:clearTimeout
ng-model-options
ng-model
andng-model-options
inindex.html
:
<input type="text" ng-model="search" ng-model-options="{ debounce: 800 }" placeholder="Enter full movie name" />
fetch()
app.js
: function fetch() { $http.get("http://www.omdbapi.com/?t=" + $scope.search + "&tomatoes=true&plot=full") .then(function(response) { $scope.details = response.data; }); $http.get("http://www.omdbapi.com/?s=" + $scope.search) .then(function(response) { $scope.related = response.data; }); }
main-info.html
:<img ng-src="{{ details.Poster=='N/A' ? 'http://placehold.it/150x220&text=N/A' : details.Poster }}" / alt="Angular&#x27; s $ httpサービスを使用してAngularjsでAPI呼び出しを行います" >
この記事は、Angularjs HTTPサービスとAPI呼び出しに関するよくある質問のセクションで終了します。 。 Codepenデモもリンクされています
以上がAngular&#x27; s $ httpサービスを使用してAngularjsでAPI呼び出しを行いますの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。