angularJS(三)內建服務
阿新 • • 發佈:2019-01-30
服務
服務是一個物件或函式,對外提供特定的功能。
1.內建服務
1、$location是對原生Javascript中location物件屬性和方法的封裝。
app.controller('demoController',['$scope','$location',function($scope,$location){
//絕對路徑
$scope.absUrl = $location.absUrl();
//返回url協議
$scope.protocol = $location.protocol();
//返回url伺服器使用的埠號
$scope .port = $location.port();
//當前路徑
$scope.path = $location.path();
//返回一個url的錨部分:第一個#後面的內容
$scope.hash = $location.hash();
//返回url的查詢字串部分
$scope.search = $location.search();
}]);
2、timeout&interval對原生Javascript中的setTimeout和setInterval進行了封裝。
app.controller('demoController',['$scope' ,'$timeout','interval',function($scope,$timeout,$interval){
$timeout(function(){
$scope.time = new Date();
},2000);
$interval(function(){
$scope.time = new Date();
},1000);
}]);
3、$log列印除錯資訊
app.controller('demoController',['$scope','$log',function($scope,$log){
$log.log('列印資訊' );
$log.info('普通訊息');
$log.warn('警告資訊');
$log.error('錯誤資訊');
$log.debug('除錯資訊');
}]);
4.
//$http本質是對XMLHttperRequest物件封裝
app.controller('demoController',['$scope','$http',function($scope,$http){
$http({
url:'example.php',//請求地址
method:'post',//請求方式也可以為get
params:{//會被轉換成查詢字串追加在URL後面。如果值不是字串,會被JSON序列化。
'name':'ari'
//引數會轉為?name=ari的形式
},
data:{name:'itcast',age:10},//post傳參
header:{//請求頭資訊
'Content-Type':'application/x-www-form-urlencoded'
}
}).success(function(data,status,headers,config){
//data響應體 status 相應的狀態值
headers是頭資訊的getter函式 ,可以結束一個引數,用來獲取對應名字值
config 是用來生成原始請求的完整設定物件。
}).error(function(data,status,headers,config){
//失敗回掉
});
}]);
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.now;
}]);
2、service方法
App.service('showTime', ['$filter', function ($filter) {
var now = new Date();
this.now = $filter('date')(now,'yyyy/MM/dd');
}]);
App.controller('DemoController', ['$scope', 'showTime', function($scope, showTime) {
$scope.now = showTime.now;
}]);
3、value方法定義常量 在介紹服務時曾提到服務本質就是一個物件或函式,所以自定義服務就是要返回一個物件或函式以供使用。
app.value('author','itcast');
app.controller('DemoController', ['$scope', 'atuhor',function($scope,author){
$scope.author = author;
}]);