angular.js 服务(Service)

AngularJS中为我们提供了众多的内置服务,通过这些内置服务可以轻松的实现一些常用功能。下面对Angular中常用的内置服务进行一下总结。

1.$location服务

$location服务解析在浏览器地址栏中的URL(基于window.location)并且让URL在你的应用中可用。改变在地址栏中的URL会作用到$location服务,同样的,改变$location服务也会改变浏览器的地址栏。(可以使用$location进行重定向等操作)

当浏览器的URL改变时,不会重新加载整个页面。如果想要加载整个页面,需要使用$window.lacation.href。

$location服务用于返回当前页面的URL地址,示例代码如下:
var app = angular.module('myApp', []); 
app.controller('customersCtrl', function($scope, $location) { 
 $scope.myUrl = $location.absUrl(); 
}); 
这里为$scope对象定义了myUrl变量,然后利用$location服务读取到了URL地址并存储到myUrl中。

2..$http服务

 

$http 是 AngularJS 中最常用的服务,它经常用于服务器的数据传输。下面的例子中服务向服务器发送请求,应用响应服务器传送过来的数据。

var app = angular.module('myApp', []); 
app.controller('myCtrl', function($scope, $http) { 
 $http.get("welcome.htm").then(function (response) { 
  $scope.myWelcome = response.data; 
 }); 
});

我们可以使用内置的$http服务直接同外部进行通信。$http服务只是简单的封装了浏览器原生的XMLHttpRequest对象。

1).链式调用

$http服务是只能接受一个参数的函数,这个参数是一个对象,包含了用来生成HTTP请求的配置内容。这个函数返回一个promise对象,具有success和error两个方法。

$http({
url:'data.json',
method:'GET'
}).success(function(data,header,config,status){
//响应成功
}).error(function(data,header,config,status){
//处理响应失败
});

 2).返回一个promise对象

var promise=$http({
method:'GET',
url:"data.json"
});

由于$http方法返回一个promise对象,我们可以在响应返回时用then方法来处理回调。如果使用then方法,会得到一个特殊的参数,它代表了相应对象的成功或失败信息,还可以接受两个可选的函数作为参数。或者可以使用success和error回调代替。

promise.then(function(resp){
//resp是一个响应对象
},function(resp){
//带有错误信息的resp
});

 或者:

promise.success(function(data,status,config,headers){
//处理成功的响应
});
promise.error(function(data,status,hedaers,config){
//处理失败后的响应
});

 then()方法与其他两种方法的主要区别是,它会接收到完整的响应对象,而success()和error()则会对响应对象进行析构。

3).快捷的get请求

(1)$http.get('/api/users.json');

get()方法返回HttpPromise对象。

还可以发送比如:delete/head/jsonp/post/put 函数内可接受参数

(2)以再发送jsonp请求举例说明: 为了发送JSONP请求,其中url必须包含JSON_CALLBACK字样。

jsonp(url,config) 其中config是可选的

 

var promise=$http.jsonp("/api/users.json?callback=JSON_CALLBACK");

4).也可以将$http当做函数来使用,这时需要传入一个设置对象,用来说明如何构造XHR对象。

$http({
method:'GET',
url:'/api/users.json',
params:{
'username':'tan'
});

其中设置对象可以包含以下主要的键:

(1)method

可以是:GET/DELETE/HEAD/JSONP/POST/PUT

(2)url:绝对的或者相对的请求目标
(3)params(字符串map或者对象)
这个键的值是一个字符串map或对象,会被转换成查询字符串追加在URL后面。如果值不是字符串,会被JSON序列化。
比如这个:

//参数会转为?name=ari的形式
$http({
params:{'name':'ari'}
});

(4)data(字符串或者对象)

这个对象中包含了将会被当作消息体发送给服务器的数据。通常在发送POST请求时使用。

从AngularJS 1.3开始,它还可以在POST请求里发送二进制数据。要发送一个blob对象,你可以简单地通过使用data参数来传递它。
例如:

var blob=new Blob(['Hello world'],{type:'text/plain'});
$http({
method:'POST',
url:'/',
data:blob
});

4).响应对象

AngularJS传递给then()方法的响应对象包含了四个属性。

data

这个数据代表转换过后的响应体(如果定义了转换的话)

status

响应的HTTP状态码

headers

这个函数是头信息的getter函数,可以接受一个参数,用来获取对应名字值

例如,用如下代码获取X-Auth-ID的值:

$http({
method: 'GET',
url: '/api/users.json'
}).then (resp) {
// 读取X-Auth-ID
resp.headers('X-Auth-ID');
});

config

这个对象是用来生成原始请求的完整设置对象。

statusText(字符串)

这个字符串是响应的HTTP状态文本。

5).缓存HTTP请求

默认情况下,$http服务不会对请求进行本地缓存。在发送单独的请求时,我们可以通过向$http请求传入一个布尔值或者一个缓存实例来启用缓存。

$http.get('/api/users.json',{ cache: true })
.success(function(data) {})
.error(function(data) {});

第一次发送请求时,$http服务会向/api/users.json发送一个GET请求。第二次发送同一个GET请求时,$http服务会从缓存中取回请求的结果,而不会真的发送一个HTTP GET请求。

在这个例子里,由于设置了启用缓存,AngularJS默认会使用$cacheFactory,这个服务是AngularJS在启动时自动创建的。

 

如果想要对AngularJS使用的缓存进行更多的自定义控制,可以向请求传入一个自定义的缓存实例代替true。

 

3.$timeout()服务和$interval()服务

 

这两个服务的功能对应的是javascript中的setTimeout()和setTimeInterval函数。一个简单的实时更新时间例子如下:

app.controller('myCtrl', function($scope, $interval) { 
 $scope.theTime = new Date().toLocaleTimeString(); 
 $interval(function () { 
  $scope.theTime = new Date().toLocaleTimeString(); 
 }, 1000); 
}); 

除了Angular中提供的内置服务外,我们也可以自己定义服务,利用service即可,下面是一个定义服务的基本代码框架:

app.service('hexafy', function() { 
 this.myFunc = function (x) { 
  return x.toString(16); 
 } 
}); 

 定义好服务后,我们可以像使用内置的Angular服务一样使用它:

app.controller('myCtrl', function($scope, hexafy) { 
 $scope.hex = hexafy.myFunc(255); 
});

 angular.js 实例:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="https://cdn.static.runoob.com/libs/angular.js/1.4.6/angular.min.js"></script>
</head>
<body>

<div ng-app="myApp" ng-controller="siteCtrl"> 
<ul>
  <li ng-repeat="x in names">
    {{ x.Name + ', ' + x.Country }}
  </li>
</ul>
</div>

<script>
var app = angular.module('myApp', []);
app.controller('siteCtrl', function($scope, $http) {
  $http.get("http://www.runoob.com/try/angularjs/data/sites.php")
  .success(function (response) {$scope.names = response.sites;});
});
</script>
</body>
</html>

存储在web服务器上的json文件

http://www.runoob.com/try/angularjs/data/sites.php

{
    "sites": [
        {
            "Name": "菜鸟教程",
            "Url": "www.runoob.com",
            "Country": "CN"
        },
        {
            "Name": "Google",
            "Url": "www.google.com",
            "Country": "USA"
        },
        {
            "Name": "Facebook",
            "Url": "www.facebook.com",
            "Country": "USA"
        },
        {
            "Name": "微博",
            "Url": "www.weibo.com",
            "Country": "CN"
        }
    ]
}

 结果为:

  • 菜鸟教程, CN
  • Google, USA
  • Facebook, USA
  • 微博, CN

实例解析:

AngularJS 应用通过 ng-app 定义。应用在 <div> 中执行。

ng-controller 指令设置了 controller 对象 名。

函数 customersController 是一个标准的 JavaScript 对象构造器

控制器对象有一个属性: $scope.names

$http.get() 从web服务器上读取静态 JSON 数据

服务器数据文件为:  http://www.runoob.com/try/angularjs/data/sites.php

当从服务端载入 JSON 数据时,$scope.names 变为一个数组。

猜你喜欢

转载自455935725.iteye.com/blog/2359295