第8章 服务

服务是一个对象或函数,对外提供特定的功能。

8.1 内建服务

1. $location是对原生Javascript中location对象属性和方法的封装。

  // $location内置服务
  // AngularJS 专门提供了一个帮你获URL地址一个服务
  App.controller('DemoController', ['$scope', '$location', function($scope, $location) {
    $scope.title = '学习$location服务';
	// $location就是angularJS提前封装好的
	// 提供获取地址相关信息的服务
	// console.log($location);
	//绝对路径
	$scope.absUrl = $location.absUrl();
	//相对路径
	$scope.url = $location.url();
	//主页
	$scope.host = $location.host();
	//查询字符串
	$scope.search = $location.search();
	//哈希值
	$scope.hash = $location.hash();
    //协议
	$scope.protocol = $location.protocol();
    //端口
	$scope.port = $location.port();
  }]);

2. $timeout&$interval对原生Javascript中的setTimeout和setInterval进行了封装。

//注入声明依赖
App.controller('DemoController', ['$scope', '$timeout', '$intervall', function($scope, $timeout, $interval){
    $timeout(function(){
		$scope.time = new Date();
	}, 2000);

	$interval(function(){
		$scope.time = new Date();
	}, 1000);
}]);


3. $filter在控制器中格式化数据。

//使用过滤器服务
App.controller('DemoController', ['$scope', '$filter', function ($scope, $filter) {
	//原始信息
	$scope.content = 'my name is angular';
	//创建过滤器
	var uppercase = $filter('uppercase');
	//格式化数据
	$scope.content = uppercase($scope.content);
}]);

4. $log打印调试信息

//使用日志服务
App.controller('DemoController', ['$scope', '$log', function(){
	$log.log('日志');
	$log.info('信息');
	$log.warn('警告');
	$log.error('错误');
	$log.debug('调试');
}]);

5. $http用于向服务端发起异步请求

//使用$http服务
App.controller('DemoController', ['$scope', '$http', '$log', function ($scope, $http, $log) {
	//发起异步请求
	$http({
		method: 'post',  //请求方式
		url: 'example.php',  //请求地址
		data: {name: 'angular', age: 10},  //请求主体
		headers: {  //请求头信息
			'Content-Type': 'application/x-www-form-urlencoded'
		},
	}).success(function (data, states, headers, config) {
		//success code
	}).error(function(data, states, headers, config){});
		//失败回调
}]);
  • 同时还支持多种快捷方式如$http.get()、$http.post()、$http.jsonp。
  • 注:各参数含义见代码注释。

8.2 自定义服务

通过上面例子得知,所谓服务是将一些通用性的功能逻辑进行封装方便使用,AngularJS允许将自定义服务。

1. factory方法

//自定义服务显示日期
App.factory('showTime', ['$filter', function($filter){
	var now = new Date();
	now = $filter('date')(now, 'yyyy/MM/dd');
	return now;
}]);
//声明依赖调用服务
App.controller('DemoController', ['$scope','showTime', function($scope, showTime){
	$scope.now = showTime;
}]);

2. service方法

//自定义服务显示日期
App.service('showTime', ['$filter', function($filter){
	var now = new Date();
	this.now = $filter('date')(now, 'yyyy/MM/dd');
	return now;
}]);
//声明依赖调用服务
App.controller('DemoController', ['$scope','showTime', function($scope, showTime){
	$scope.now = showTime;
}]);

3. value方法定义常量

//自定义常量服务
App.value('author', 'angular');

//声明依赖调用服务
App.controller('DemoController', ['$scope', 'author', function($scope, auther){
	$scope.author = author;
}]);

  • 在介绍服务时曾提到服务本质就是一个对象或函数,所以自定义服务就是要返回一个对象或函数以供使用。
posted on 2018-03-11 16:51  luoyu113  阅读(146)  评论(0)    收藏  举报