为什么要使用$ HTTP的角度,而不是jQuery的AJAX? [英] Why use $http in Angular instead of jquery's ajax?

查看:142
本文介绍了为什么要使用$ HTTP的角度,而不是jQuery的AJAX?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不明白何时使用角过的jQuery的Ajax请求。

例如,我为什么要使用:

 函数ItemListCtrl($范围,$ HTTP){
    $ http.get('example.com/items)。成功(功能(数据){
    $ scope.items =数据;
  }
}
 

相反

 函数ItemListCtrl($范围){
        $阿贾克斯({类型:GET,网址:example.com/items,
        成功:函数(结果){
                             $ scope.items =数据;
                    }
    });
   }
 

??

解决方案

我的理解是,有一对夫妇的原因:首先是$​​ P $ pferred:

  • $ HTTP是可检验的。它实际上可以存根出它使用和测试$ HTTP请求,而不后端的实际上的发送请求。
  • $ HTTP做一些常见的东西给你,如POST请求设置内容类型为应用程序/ JSON的为您服务。
  • $ HTTP返回一个承诺的角度类似于其他领域,这意味着.success,.done与角度一致。 jQuery的也允许类似,但是语法稍有不同。
  • $ HTTP成功和错误回调将角内执行。如果你使用jQuery,那么它可能需要调用$申请,这可能会非常棘手的情况。
  • $ HTTP工作没有jQuery的。所以,如果你没有一些其他的原因包括jQuery的,你可能通过使用$ HTTP节省几k。
  • $ HTTP较短。主观的,但就个人而言,它读取更好的给我。

除了这些,但是,你一般应能够做到无论是。

I don't understand when to use Angular over jquery for ajax requests.

For example, why should I use:

function ItemListCtrl ($scope, $http) {
    $http.get(‘example.com/items').success(function (data) {
    $scope.items = data;
  }
}

Instead of

  function ItemListCtrl ($scope) {
        $.ajax({type: "GET", url: 'example.com/items',
        success: function (result) {                    
                             $scope.items = data;
                    }
    });
   }

??

解决方案

My understanding is that there are a couple reasons the first is preferred:

  • $http is testable. It's actually possible to stub out the backend that it uses and test $http requests without actually sending requests.
  • $http does some common "stuff" for you, such as setting the content type to 'application/json' for you on POST requests.
  • $http returns a "promise" similar to other areas in angular, which means .success, .done are consistent with angular. jquery also allows for similar, but the syntax is slightly different.
  • $http success and error callbacks will execute inside of angular. If you use jQuery, then it might be necessary to call $apply, which can be tricky in some cases.
  • $http works without jQuery. So if you don't have some other reason to include jQuery, you could possibly save a few k by using $http.
  • $http is shorter. Subjective, but personally, it reads better to me.

Aside from those, though, you generally should be able to do either.

这篇关于为什么要使用$ HTTP的角度,而不是jQuery的AJAX?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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