首页 > web前端 > js教程 > 使用Angular的$ HTTP服务在Angularj中进行API调用

使用Angular的$ HTTP服务在Angularj中进行API调用

Jennifer Aniston
发布: 2025-02-20 09:42:11
原创
966 人浏览过

Making API Calls in AngularJS using Angular's $http service

>本文演示了如何使用AngularJS向远程API提出HTTP请求并使用JSON响应更新视图。 它利用Angular's $http服务和数据绑定。

密钥概念:

  • $http.get用于将获取请求发送到API,包括查询字符串。 响应存储在模型中(在此示例中detailsrelated)。
  • > ngModelOptionsdebounce>通过延迟模型更新(在这种情况下为800ms)。
  • 服务:>监视更改的模型,触发数据获取。$watch search>
  • 的承诺:
  • 现代错误使用承诺而不是不弃用的/。error()方法。 .then() .success()项目结构和代码亮点:
>

>该项目使用模块化结构(CSS,JS,部分,index.html)。 包括搜索输入(绑定到> and

的模型绑定到

>),以及index.html>指令加载部分视图(search> and ng-model)。 ng-model-options核心逻辑属于ng-include,特别是main-info.htmlrelated-results.html>线可确保每当搜索输入期间更改搜索输入时,

函数都会被调用。

>使用app.jsMovieController对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.htmlng-if改进&更新:related-results.html ng-repeat文章记录在2016-01-17进行的更新,包括:update()>

>用/替换

>

debounce和

>。
  • 更新以使用setTimeout进行保证处理。clearTimeout> ng-model-options修复破损的海报图像。$watch
  • .then()>示例代码片段:
    • ng-modelng-model-optionsin index.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的$ HTTP服务在Angularj中进行API调用" >
    登录后复制

    >本文以有关AngularJS HTTP服务和API呼叫的经常询问的问题的一部分结束。 也链接了Codepen演示。

以上是使用Angular的$ HTTP服务在Angularj中进行API调用的详细内容。更多信息请关注PHP中文网其他相关文章!

本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板