高效利用Angular中內(nèi)置服務$http、$location等

字號:


    這篇文章主要介紹了如何高效利用Angular中內(nèi)置服務,大家知道的Angular內(nèi)置服務有哪些,感興趣的小伙伴們可以參考一下
    AngularJS中為我們提供了眾多的內(nèi)置服務,通過這些內(nèi)置服務可以輕松的實現(xiàn)一些常用功能。下面對Angular中常用的內(nèi)置服務進行一下總結(jié)。
    1.$location服務
    $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 中最常用的服務,它經(jīng)常用于服務器的數(shù)據(jù)傳輸。下面的例子中服務向服務器發(fā)送請求,應用響應服務器傳送過來的數(shù)據(jù)。
    var app = angular.module('myApp', []); 
    app.controller('myCtrl', function($scope, $http) { 
     $http.get("welcome.htm").then(function (response) { 
      $scope.myWelcome = response.data; 
     }); 
    });
    3.$timeout()服務和$interval()服務
    這兩個服務的功能對應的是javascript中的setTimeout()和setTimeInterval函數(shù)。一個簡單的實時更新時間例子如下:
    app.controller('myCtrl', function($scope, $interval) { 
     $scope.theTime = new Date().toLocaleTimeString(); 
     $interval(function () { 
      $scope.theTime = new Date().toLocaleTimeString(); 
     }, 1000); 
    }); 
    除了Angular中提供的內(nèi)置服務外,我們也可以自己定義服務,利用service即可,下面是一個定義服務的基本代碼框架:
    app.service('hexafy', function() { 
     this.myFunc = function (x) { 
      return x.toString(16); 
     } 
    }); 
    定義好服務后,我們可以像使用內(nèi)置的Angular服務一樣使用它:
    app.controller('myCtrl', function($scope, hexafy) { 
     $scope.hex = hexafy.myFunc(255); 
    });
    以上就是針對Angular中常用的內(nèi)置服務進行的匯總,希望對大家的學習有所幫助。