>本文演示瞭如何使用AngularJS向遠程API提出HTTP請求並使用JSON響應更新視圖。 它利用Angular's $http
服務和數據綁定。
密鑰概念:
$http.get
:用於將獲取請求發送到API,包括查詢字符串。 響應存儲在模型中(在此示例中details
和related
)。
ngModelOptions
:debounce
>通過延遲模型更新(在這種情況下為800ms)。
$watch
search
> .then()
.success()
項目結構和代碼亮點:>該項目使用模塊化結構(CSS,JS,部分,index.html)。 包括搜索輸入(綁定到> and
的模型綁定到>),以及index.html
>指令加載部分視圖(search
> and ng-model
)。
ng-model-options
核心邏輯屬於ng-include
,特別是main-info.html
。 related-results.html
>線可確保每當搜索輸入期間更改搜索輸入時,
>使用app.js
MovieController
對OMDB API進行兩個API調用(一個用於主要電影詳細信息,一個用於相關電影)。 然後將響應分配給$watch('search', fetch)
>和fetch()
。 fetch()
>功能處理相關電影標題的單擊,更新$http.get
型號。 $scope.details
>
$scope.related
部分視圖(update()
和search
)使用Angular的數據綁定來顯示電影信息。
),以處理加載狀態和缺少海報圖像。 main-info.html
>使用related-results.html
的相關電影迭代,然後單擊。
main-info.html
ng-if
改進&更新:related-results.html
ng-repeat
文章記錄在2016-01-17進行的更新,包括:update()
>
>用/替換
>debounce和
>。setTimeout
進行保證處理。 clearTimeout
>
ng-model-options
修復破損的海報圖像。 $watch
.then()
>示例代碼片段:ng-model
和ng-model-options
in index.html
:<code class="language-html"><input type="text" ng-model="search" ng-model-options="{ debounce: 800 }" placeholder="Enter full movie name"></code>
fetch()
app.js
中的函數
<code class="language-javascript">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; }); }</code>
main-info.html
><code class="language-html"><img ng-src="{{ details.Poster=='N/A' ? 'http://placehold.it/150x220&text=N/A' : details.Poster }}" alt="使用Angular的$ HTTP服務在Angularj中進行API調用" ></code>
>本文以有關AngularJS HTTP服務和API呼叫的經常詢問的問題的一部分結束。 也鏈接了Codepen演示。
以上是使用Angular的$ HTTP服務在Angularj中進行API調用的詳細內容。更多資訊請關注PHP中文網其他相關文章!