加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

angularjs – 在Angular.js中进行AJAX调用的最佳做法是什么?

发布时间:2020-12-17 09:21:17 所属栏目:安全 来源:网络整理
导读:我正在读这篇文章: http://eviltrout.com/2013/06/15/ember-vs-angular.html 它说, Due to it’s lack of conventions,I wonder how many Angular projects rely on bad practices such as AJAX calls directly within controllers? Due to dependency inj
我正在读这篇文章: http://eviltrout.com/2013/06/15/ember-vs-angular.html

它说,

Due to it’s lack of conventions,I wonder how many Angular projects
rely on bad practices such as AJAX calls directly within controllers?
Due to dependency injection,are developers injecting router
parameters into directives? Are novice AngularJS developers going to
structure their code in a way that an experienced AngularJS developer
believes is idiomatic?

我实际上是从我的Angular.js控制器进行$ http调用。为什么这是一个坏的做法?那么,最好的做法是使用$ http调用呢?为什么?

编辑:这个答案主要集中在版本1.0.X.为了防止混乱,它被改变以反映当今版本的Angular的最佳答案,截至今天,2013-12-05。

想法是创建一个服务,返回一个promise返回的数据,然后调用它在你的控制器,并处理承诺,填充你的$ 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',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();
});

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读