14 Built-in Services 1

Built-in service 1

In Angular, services are created as singleton objects when they are needed, and are only cleared when the application life cycle ends (closes the browser). And controllers are destroyed when they are not needed.

Overview of some built-in services in Angular

In AngularJS, a service is a function or object that can be used in your AngularJS application.

name describe
$window Encapsulates the window object.
$document window.documentThe jqLite encapsulation of the browser object mainly operates on the DOM. It $documentis equivalent to angular.element(document), but it should be noted that the references of the two are not equal, and the original document object can be obtained by taking the 0 subscript: $document[0] === document, that is, the reference is equal, because it is a reference to the browser The encapsulation of the document object
$log Simple service for printing logs. The default implementation is to safely write information to the browser's console (if it exists).
$interval window.setIntervalAngular wrapper form.
$timeout window.setTimeoutAngular wrapper form
$rootScope the root scope of the application
$http $httpIs a core service of Angular, which facilitates the browser to interact with the remote HTTP server through the XMLHttpRequest object or JSONP.
$location $locationThe service resolves the url (based on) the browser address window.locationand makes the url available in the application. Reflect changes to the URL in the address bar to the $locationservice and $locationchanges to the browser address bar.
$anchorScroll According to HTML5 rules, when this function is called, it checks the hash of the current url and scrolls to the corresponding element.
$q A service to help handle asynchronously executing functions. When they're done processing, use their return value (or exception).
$compile Compiles an HTML string or DOM template, yielding a function that links the scope and template together.
$interpolate Compile a string into an interpolation function. The HTML Compilation Service uses this service to perform data binding.
$parse Convert Angular expressions to functions.
$templateRequest $templateRequestThe service runs for security detection, and then uses $httpthe provided template to download, and after success, stores the content in $templateCacheit. If the HTTP request fails or the response data of the HTTP request is empty, an $compileerror will be thrown (by setting the second parameter of this function to true). The note is that $templateCachethe content of , is trusted, so the call $sce.getTrustedUrl(tpl)is omitted when tpl is of type string and $templateCachehas a matching item.
$templateCache The first time a template is used, it is loaded into the template cache for fast retrieval. You can load template tags directly into the cache, or through a $templateCacheservice.
$sce $sceService is a strict context escape service provided by AngularJs.
$sceDelegate $sceDelegateis an AngularJs service that provides strict context escaping services for the $sce service.
$animate $animateServices provide basic DOM manipulation functionality such as inserting, removing, and moving elements in the DOM, as well as adding and removing classes. This service is the core service of ngAnimate and provides high-level animations for CSS and Javascript.

$log

$logThe service is very simple, it is more advanced console.log, it provides 5 methods:log、warn、info、error、debug

<div ng-controller="LogController">
<p>Reload this page with open console, enter text and hit the log button...</p>
<label>Message:
<input type="text" ng-model="message"/>
</label>
<button ng-click="$log.log(message)">log</button>
<button ng-click="$log.warn(message)">warn</button>
<button ng-click="$log.info(message)">info</button>
<button ng-click="$log.error(message)">error</button>
<button ng-click="$log.debug(message)">debug</button>
</div>
angular.module('myDemo', [])
.controller('LogController', function ($scope, $log) {
$scope.$log = $log;
});

Effect (browser F12 to open the console):

这里写图片描述

$ timeout and $interval

$timeout(fn, [delay], [invokeApply],[Pass]);

$interval(fn, delay, [count], [invokeApply], [Pass]);

parameter Types of describe
fn function()= A function that will be deferred.
delay num Delay time in milliseconds.
count num repeat times
invokeApply (optional) boolean If set to false, dirty value detection is skipped, otherwise $apply will be called.
Pass (optional) * Additional arguments to the executed function.
$timeout(function() {
$scope.myHeader = "How are you today?";
}, 2000);
$interval(function() {
$scope.theTime = new Date().toLocaleTimeString();
}, 1000);

$timeoutAnd is a service that comes with AngularJS, and the usage of the and function in $intervalnative js is basically the same. But there are two differences to note:setTimeoutsetInterval

  • Difference one:

原生js中的两个函数,如果在AngularJS中使用并且在回调函数中需要使用$scope服务的话,我们需要用$angular.$apply把回调函数包起来,因为这里setTimeout函数被AngularJS当作是外部函数了。就像这样:

// 错误的写法示例(使用setTimeout却没有用$apply):
angular.module('myDemo', [])
.controller('firstController', ['$scope', function ($scope) {
setTimeout(function () {
console.log('before'); // 正常输出before
$scope.name = "My name have been changed."; // 这一句不被执行
console.log('after'); // 正常输出after
}, 2000);
}]);
// 正确的写法示例
setTimeout(function () {
console.log('before'); // 正常输出before
$scope.$apply(function () {
$scope.name = "My name have been changed."; // 正确显示
});
console.log('after'); // 正常输出after
}, 2000);

所以,在AngularJS中,最好不要用setTimeout或setInterval,而是用那两个AngularJS系统服务。

  • 区别二:取消的方式不大一样,比如timeout:
// setTimeout
var id = setTimeout(func, 2000); // 返回该timeout的id
clearTimeout(id); // 使用clearTimeout

// $timeout服务
var promise = $timeout(f, 2000); // 返回一个promise对象
$timeout.cancel(promise); // 还是要使用服务,它的cancel方法,返回boolean

$cacheFactory和$cacheFactory.Cache

$cacheFactory是应用程序一个会话(Session)中的缓存服务,以key-value对的方法存储一些临时数据。它跟浏览器本地缓存localStorage是不一样的。$cacheFactory在用户删除当前会话(比如强制刷新页面)之后,缓存的数据就被清空了。

$cacheFactory.Cache:一个用于存储和检索数据的缓存对象。主要使用$http和脚本指令来缓存模板和其他数据。

要得到一个缓存实例,用id来区分,比如我想取id为’firstCache’的缓存:

var cache = $cacheFactory('firstCache');

方法 描述
put(key,value); 在缓存对象中插入一个键值对(key,value)。
key:string类型,缓存对象中的值名称。
value:所有类型,缓存对象中的值。
get(key); 在缓存对象中通过指定key获取对应的值。如果不存在这个key的话,会返回undefined
remove(key); 在缓存对象中通过指定key删除对应的值。
removeAll(); 删除缓存对象中所有的键值对。
destroy(); 销毁这个缓存对象。
info(); 获取缓存对象信息(id,size)。
(function () {
angular.module("Demo", [])
.controller("testCtrl", ["$cacheFactory",testCtrl]);
function testCtrl($cacheFactory) {
var myCache = $cacheFactory("my-cache");
myCache.put("cache", "This is cache-content");
myCache.put("another-cache", "This is another cache-content");
var getCache = myCache.get("cache"); //This is cache-content
var getInfo = myCache.info();//{id: "my-cache", size: 2}
myCache.remove("another-cache");
getInfo = myCache.info();//{id: "my-cache", size: 1}
myCache.removeAll();
getInfo = myCache.info();//{id: "my-cache", size: 0}
myCache.destroy();
getInfo = myCache.info();//{size: 0}
};
}());

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324682898&siteId=291194637