栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

在Angular.js中进行AJAX调用的最佳实践是什么?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

在Angular.js中进行AJAX调用的最佳实践是什么?

编辑:这个答案主要集中在版本1.0.X。 为避免混淆,已对其进行了更改,以反映截至2013年12月5日的所有当前Angular版本的最佳答案。

这个想法是创建一个服务,该服务向返回的数据返回一个承诺,然后在您的控制器中调用它并在其中处理该承诺以填充$ scope属性。

服务

module.factory('myService', function($http) {   return {        getFoos: function() {  //return the promise directly.  return $http.get('/foos') .then(function(result) {      //resolve the promise as the data      return result.data;  });        }   }});

控制器:

处理promise的

then()
方法并从中获取数据。设置$ scope属性,然后执行您可能需要做的其他事情。

module.controller('MyCtrl', function($scope, myService) {    myService.getFoos().then(function(foos) {        $scope.foos = foos;    });});

视野中的承诺解决方案(仅1.0.X版):

在原始答案的目标Angular 1.0.X中,Promise将由View进行特殊处理。当他们解析时,其解析值将绑定到视图。 在1.2.X中已弃用

module.controller('MyCtrl', function($scope, myService) {    // now you can just call it and stick it in a $scope property.    // it will update the view when it resolves.    $scope.foos = myService.getFoos();});


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/636136.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号