在 Angular.js 中进行 AJAX 调用的最佳实践是什么? [英] What is the best practice for making an AJAX call in Angular.js?

查看:29
本文介绍了在 Angular.js 中进行 AJAX 调用的最佳实践是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读这篇文章:http://eviltrout.com/2013/06/15/ember-vs-angular.html

它说,

由于缺乏约定,我想知道有多少 Angular 项目直接在控制器内依赖不良做法,例如 AJAX 调用?由于依赖注入,开发者是否注入路由器参数变成指令?AngularJS 开发新手会去吗以经验丰富的 AngularJS 开发人员的方式构建他们的代码相信是惯用的?

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 调用的最佳做法是什么?为什么?

I am actually making $http calls from my Angular.js controller. Why is it a bad practice? What is the best practice for making $http calls then? and why?

推荐答案

此答案主要针对 1.0.X 版.为了防止混淆,它已被更改以反映截至今天(2013 年 12 月 5 日)所有当前版本的 Angular 的最佳答案.

我们的想法是创建一个服务,该服务返回对返回数据的承诺,然后在您的控制器中调用它并处理那里的承诺以填充您的 $scope 属性.

The idea is to create a service that returns a promise to the returned data, then call that in your controller and handle the promise there to populate your $scope property.

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 属性,然后执行您可能需要执行的任何其他操作.

The Controller:

Handle the promise's then() method and get the data out of it. Set the $scope property, and do whatever else you might need to do.

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

In-View Promise 解决方案(仅限 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();
});

这篇关于在 Angular.js 中进行 AJAX 调用的最佳实践是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆