1. 程式人生 > >AngularJS-常用服務

AngularJS-常用服務

Angular 內建了很多服務,例如$location服務,用來和瀏覽器的位址列進行互動;$root服務,用來根據URL地址的變換切換檢視;還有$http服務,用來和伺服器進行互動。

 $routeProvider

使用 $routeProvider繫結路由與檢視。

我們可以利用路由服務定義這樣一種東西:對於瀏覽器所指向的特定URL,Angular將會載入並顯示一個模板,並例項化一個控制器來為模板提供內容。

//執行嚴格的js語法檢查
'use strict';


angular
//新建模組,應用名是cepWebApp,接著是依賴的模組。
  .module('cepWebApp', [
    'ngCookies',
    'ngResource',
    'ngSanitize',
    'ngRoute',
    'cepWebApp.configs',
    'ui.bootstrap',
    'toastr'
  ])
  //開始配置路由與對應的html模板檢視
  .config(function ($routeProvider) {
    $routeProvider
      .when('/', {
        redirectTo: '/dataSource'
      })
      .when('/dataSource', {
        templateUrl: 'views/dataSource/dataSourceConfig.html',
        controller: 'DataSourceConfigCtrl'
      })
      .when('/counter', {
        templateUrl: 'views/counter/counter.html',
        controller: 'CounterCtrl'
      })
      .when('/rule', {
        templateUrl: 'views/rule/rule.html',
        controller: 'RuleCtrl'
      })
      .when('/statistics', {
        templateUrl: 'views/statistics/statistics.html',
        controller: 'StatisticsCtrl'
      })
	  //不滿足上面when時的情況
      .otherwise({
        redirectTo: '/'
      });
  })


;

切換檢視的原理:Angular發起下圖的請求:


XHR:SmlHttpRequest,本質是Ajax。

注意URL的變化,是在'#'後面的,這個是HTML標準的頁內標籤,Angular通過這個標準實現了路由子頁面這一自己的目的。


$http

$http.get(url) : get方式獲取url返回。
<!DOCTYPE html>
<html>
<body>

<div ng-app="" ng-controller="customersController"> 


<h3>  得到的JSON資料 </h3>
<br>
<table class="table table-striped">
  <thead>
    <tr>
      <th>名</th>
      <th>城市</th>
      <th>國家</th>
    </tr>
  </thead>
  <tbody>
    <tr ng-repeat="x in names">

      <td>{{ x.Name }}</td>
 <td>{{ x.City}}</td>
      <td>{{ x.Country }}</td>
    </tr>
  </tbody>
</table>

</div>

<script>
function customersController($scope,$http) {
  $http.get("http://www.w3cschool.cc/try/angularjs/data/Customers_JSON.php")//這個http請求會拿到純文字返回,裡面是json內容。
  .success(function(response) {$scope.names = response;});//response就是json格式的資料,相當於把json反序列化為了js物件。
}
</script>

<script src="http://apps.bdimg.com/libs/angular.js/1.2.15/angular.min.js"></script>

</body>
</html>
			

$http拿到的json內容見下:

[ { "Name" : "Alfreds Futterkiste", "City" : "Berlin", "Country" : "Germany" }, { "Name" : "Berglunds snabbköp", "City" : "Luleå", "Country" : "Sweden" }, { "Name" : "Centro comercial Moctezuma", "City" : "México D.F.", "Country" : "Mexico" }, { "Name" : "Ernst Handel", "City" : "Graz", "Country" : "Austria" }, { "Name" : "FISSA Fabrica Inter. Salchichas S.A.", "City" : "Madrid", "Country" : "Spain" }, { "Name" : "Galería del gastrónomo", "City" : "Barcelona", "Country" : "Spain" }, { "Name" : "Island Trading", "City" : "Cowes", "Country" : "UK" }, { "Name" : "Königlich Essen", "City" : "Brandenburg", "Country" : "Germany" }, { "Name" : "Laughing Bacchus Wine Cellars", "City" : "Vancouver", "Country" : "Canada" }, { "Name" : "Magazzini Alimentari Riuniti", "City" : "Bergamo", "Country" : "Italy" }, { "Name" : "North/South", "City" : "London", "Country" : "UK" }, { "Name" : "Paris spécialités", "City" : "Paris", "Country" : "France" }, { "Name" : "Rattlesnake Canyon Grocery", "City" : "Albuquerque", "Country" : "USA" }, { "Name" : "Simons bistro", "City" : "København", "Country" : "Denmark" }, { "Name" : "The Big Cheese", "City" : "Portland", "Country" : "USA" }, { "Name" : "Vaffeljernet", "City" : "Århus", "Country" : "Denmark" }, { "Name" : "Wolski Zajazd", "City" : "Warszawa", "Country" : "Poland" } ]

網頁效果

$http.jsonp()

用於get請求跨域訪問獲得json。 一個例項:
$http.jsonp(
	"http://115.28.88.165/ws/qing/timeSpan"+ "?callback=JSON_CALLBACK").success(
	function(data) {
		$scope.timeSpan = data;
	}).error(function(data) {
		console.log(data);
});
JSON_CALLBACK會被框架處理,如變成“angular.callbacks._0”。
期望返回報文的Content-Type應該是application/x-javascript;內容應該是angular.callbacks._0({"name":"xiaoMing"}); 。這樣的話,data就是框架處理後的json。

$http.post()

post方式發起http請求。此時請求的Content-Type預設為  application/json;charset=UTF-8 。
var postData={"name":"xiaoHong","age":"13","book":{"name":"Physics"}};
	$http.post("http://localhost:8080/WebService/student/post",postData).success(function(data) {
		//$scope.receivedData = data;
		console.log("hehe");
		console.log(data);
	}).error(function(data) {
		console.log(data);
	});

$http.get()與$http.post()都是有回撥的,需要的時候可以加上。

$interval(定時器)

$interval(fn, delay, [count], [invokeApply]);
說明: fn是函式,delay是定時器的間隔,單位是毫秒。count為可選引數,表明,執行多少次後停止。
invokeApply:bool型別,If set to false skips model dirty checking, otherwise will invoke fn within the $apply block。

$q與promise(非同步執行結果)

var deferred=$q.defer();
var promise=deferred.promise;//promise用來描述非同步執行結果
if(/*成功執行*/){
	deferred.resolve();//表示成功執行
}else{
	deferred.reject();//沒有成功執行
}
promise.then(/*do something*/);//成功執行後呼叫
promise.then(/*do other thing*/);//這是第二個then,執行失敗後呼叫
/*也可以鏈式寫promise.then(/*do something*/).then(/*do other thing*/);*/
解決多個ajax請求之間的依賴,除了用回撥,還可以用promise。
// 展示爬蟲系統的下一個url並解析此url
$scope.nextDisplay = function() {
	$scope.getNextUrl().then(function success(data) {
		$scope.urlService($scope.nextUrl)
	});
}
//拿到爬蟲系統的下一個url					
$scope.getNextUrl = function() {
	var promise = $http
			.get(
					"/GraduationProjectCollect/webService/spiderService/nextUrl")
			.success(function(data) {
				$scope.nextUrl = data;//我們的目的是 這一句執行後再執行$scope.urlService($scope.nextUrl)函式
			}).error(function(data) {
				alert("獲取爬蟲系統地nextUrl失敗");
				console.log(data);
			});
	return promise;
}