>本文演示了如何使用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中文网其他相关文章!