angularjs速成学习个人理解_5$http服务

$http是一个angularjs服务,angularjs内置了很多服务方便我们开发。如果学过jquery的$.ajax函数就很好理解$http服务。

1)$http 是一个angularjs服务,用于从远程服务中读取数据

2)这个$http服务制作一个请求发送到服务器,并且返回一个响应。
3)$http提供了几个简单的方法:
* .delete(): 用于发送delete请求)
* .get(): 用于发送get请求
* .head() 用于发送head请求
* .jsonp() 用于发送jsonp请求
* .patch() 这个不是很清楚
* .post()用于发送post请求
* .put()用于发送put请求
响应回来我们可以获取一个对象。这个对象有如下属性。
.config  用于生成请求的对象。
.data    一个字符串或一个对象,它从服务器中执行响应。
.headers 用于获取头信息的函数。
.status  一个定义HTTP状态的数字。
.statusText 定义HTTP状态的字符串。
就是简单的封装了$http服务,常规项目开发时,使用较多的是原始的内置服务$http的$http({}).then(fn1, fn2)函数进行异步数据处理。fn1成功时回调函数。fn2失败时回调函数。参数为响应回来对象.

在服务器制作一个json文件,内容为json数据数组。如下:

[
	{"id":"1", "num":23, "name":"James", "position":"PF", "team":"骑士", "thumb":"james.png", "votes":1988},
	{"id":"2", "num":30, "name":"Curry", "position":"SG", "team":"勇士", "thumb":"curry.png", "votes":1865}
]

请求如下: http://localhost:63342/angulartest/data/players_data1.json

angularjs速成学习个人理解_5$http服务_第1张图片


======>

通过$http发送get请求如下代码:

				$http({
					method: "GET",
					url: "http://localhost:63342/angulartest/data/players_data1.json"
				}).then(function(resp) {
					$scope.respData = resp.data;
				}, function(resp) {
					$scope.respData = resp.statusText;
				});

成功时,在页面中显示数据用{{respData}}。成功时显示数据,失败时显示响应状态文字。

完整代码如下:




	
		
		
		$http - AngularJS Test
		
	
	
		
{{respData}}

有了这部分功能后期我们的前端数据皆可以通过json数据进行获取。





你可能感兴趣的:(angularjs速成学习个人理解_5$http服务)