angular中的$http服务
发布时间:2020-12-17 10:06:28 所属栏目:安全 来源:网络整理
导读:$http是ng内置的一个服务。是简单的封装了浏览器原生的XMLHttpRequest对象。 写法1 $http({ method: "GET" ,url: 'data.json' ,}).success( function (data,status,headers,config){ $scope.list = data; }).error( function (data,config) { // }); 实际上$
$http是ng内置的一个服务。是简单的封装了浏览器原生的XMLHttpRequest对象。
写法1 $http({ method: "GET",url: 'data.json',}).success(function(data,status,headers,config){ $scope.list = data; }).error(function(data,config) { // });
实际上$http方法返回一个promise对象,这样可以方便的进行链式调用。
于是我们可以这样
var promise = $http({ method: "GET",}) promise .success(function(data,config){ // $scope.list = data; }) .error(function(data,config) { // });
注意:
1. 如果响应状态码在200和299之间,会认为响应是成功的,success回调会被调用,否则会调用error回调。
2.如果响应结果是重定向,XMLHttpRequest会跟进这个重定向,并不会调用error回调。
写法2
使用promise对象的then方法
then()方法与其他两种方法的主要区别是,它会接收到完整的响应对象,而success()和error()则会对响应对象进行析构。个人理解是拆分了
$http({ method: "GET",url: 'data.json' }) .then(successCallback,errorCallback);
写法3 快捷写法
jQuery源码中,$.get(url,data,fn),$.post等是对$ajax的再次封装。ng类似。
$http.get('data.json').success(function(data){ $scope.list = data }) 实例:demo (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |