Angular中的缓存

缓存的功能就是加快获取内容的速度,减少重复请求,这是一项非常重要的作用。
因此,angularJS框架中,提供了专门的服务—— cacheFactory http服务中还存在缓存中可以开启缓存、自定义缓存名称.
info方法
info方法返回缓存对象的一些信息,包括大小、名称、代码如下。

var cache = $cacheFactory("test");
console.log(cache.info));

第一行创建了一个名为test的缓存对象,并将该对象保存至cache变量中;
第二行,调用了info()方法,在控制台输出缓存对象的大小和名称信息,输出内容如下。
// Obiect {id: “test”,size: 0}
因为只创建了一个名为test的缓存对象,还没有写入内存,因此,他的大小为0.

put方法
put方法可以向缓存对象中以key/value的形式添加缓存内容。

cache.put("c1","hello");
console.log(cache.put("c1","hello"));

第一行表示通过调用put方法向cache对象中添加一个键名为c1、键值为”hello”的缓存内容,整个方法还将返回添加后的键值
// hello

get方法
get方法可以获取键名对应的键值内容,
console.log(cache.get(“c1”));
console.log(cache.get(“c2”));
第一行输出键名为”c1”的对应的值,即hello
第二行,由于没有添加为”c2”的键名,因此找不到对应的键值,则返回一个undefind字符。

remove方法
remove方法可以移除指定键名的缓存

cache.remove("c1");
console.log(cache.get("c1"));

第一行表示移除键名”c1”对应的缓存内容,由于已经移除了键名为”c1”的缓存,因此将在第2行中控制台输出undefined字符。

removeAll和destory方法
removeAll方法用于移除全部的缓存内容,并重置缓存结构;
destory方法则是从$cacheFactory缓存注册表中删除所有的缓存引用条目,并重置缓存对象。

举个例子

<!DOCTYPE html>
<html ng-app="a7_4">
<head>
    <title>$cacheFactory服务创建缓存对象</title>
    <script src="../Script/angular.min.js"></script>
    <link href="Css/css7.css" rel="stylesheet" />
</head>
<body>
    <div class="frame" ng-controller="c7_4">
        <div class="show">
            <input type="text" ng-model="cname" size="6" />
            <button ng-click="cset()">设置</button>
            <button ng-click="cshow()">显示</button>
            <button ng-click="cdel()">删除</button>
            <div class="tip">缓存值是:{{cvalue}}</div>
        </div>
    </div>
    <script type="text/javascript">
        angular.module('a7_4', [])
              .service("cache", function ($cacheFactory) {
                  return $cacheFactory("test");
              })
             .controller('c7_4', function ($scope, cache) {
                 $scope.cset = function () {
                     cache.put("mytest", $scope.cname);
                 }
                 $scope.cshow = function () {
                     var tcache = cache.get("mytest");
                     $scope.cvalue = tcache ? tcache : "空值";
                 }
                 $scope.cdel = function () {
                     cache.remove("mytest");
                 }
             });
    </script>
</body>
</html>

源码解析:
①首先创建一个名为”cache”的服务,该服务返回一个名为“test”的缓存对象,用于控制器中注入。
②在控制器中,注入cache服务,获取缓存对象,同事,定义3个方法,分别绑定页面中的“设置”“显示”“删除”按钮;
③在绑定“设置”的方法中,使用put方法将文本框中的内容作为键名为”mytest”对应的键值添加到缓存中。
④在显示方法中,使用get方法先获取键名为“mytest”的缓存值,再检测该值是否为”undefined”,
如果是则显示“空值”字样,否则,显示,键名对应的缓存值;
在绑定的“删除”的方法中,使用remove方法直接移除指定键名的缓存内容。

$http服务中缓存

<!DOCTYPE html>
<html ng-app="a7_5">
<head>
    <title>$http服务中的缓存</title>
    <script src="../Script/angular.min.js"></script>
    <link href="Css/css7.css" rel="stylesheet" />
</head>
<body>
    <div class="frame" ng-controller="c7_5">
        <div class="show">
            <div class="tip">接收内容是:{{result}}</div>
            <div class="tip">缓存内容是:{{cache}}</div>
        </div>
    </div>
    <script type="text/javascript">
        angular.module('a7_5', [])
             .controller('c7_5', function ($scope, $http,
$cacheFactory) {
                 var url = 'data/cache.php';
                 var cache = $cacheFactory.get("$http");
                 $http({
                     method: 'GET',
                     url: url,
                     cache: true
                 }).success(function (data, status, headers,
config) {
                     $scope.result = data;
                     var arrResp = cache.get(url);
                     $scope.cache = arrResp[0] + "_" + arrResp[1];
                 })
             });
    </script>
</body>
</html>
为了在开启缓存后,获取缓存对象的内容,
①首先,构建控制器代码时,注入$cacheFactory服务,通过调用该服务的get方法,获取名为"$http"的缓存对象,该对象是在调用$http方法时,由angular内部自动创建的。
②在调用$http方法向服务端发送HTTP请求时,向配置对象中添加"chche"属性,并将它的属性值设置为true.
③通过这样的配置,当HTTP请求发送成功后,服务端返回的全部原始数据将自动被添加到URL为键名的缓存对象中。
④调用缓存对象中get方法,获取以URL为键名的缓存内容。从执行结果来看,这些缓存内容包含了服务端在执行HTTP请求返回客户端的全部信息,如时间、返回体和头信息等,由于是以数组形式进行保存的,因此,需要使用索引号获取指定显示的内容。

自定义$http服务中缓存

<!DOCTYPE html>
<html ng-app="a7_6">
<head>
    <title>自定义$http服务中的缓存</title>
    <script src="../Script/angular.min.js"></script>
    <link href="Css/css7.css" rel="stylesheet" />
</head>
<body>
    <div class="frame" ng-controller="c7_6">
        <div class="show">
            <div class="tip">接收内容是:{{result}}</div>
            <button ng-click="refresh()">刷新</button>
        </div>
    </div>
    <script type="text/javascript">
        angular.module('a7_6', [])
            .service("cache", function ($cacheFactory) {
                return $cacheFactory("mycache", { capacity: 3 })
            })
           .controller('c7_6', function ($scope, $http, cache) {
               var url = 'data/cache.php';
               $http({
                   method: 'GET',
                   url: url,
                   cache: cache
               }).success(function (data, status, headers,
config) {
                   $scope.result = data;
                   cache.put("c", data);
               })
               $scope.refresh = function () {
                   var _c = cache.get("c");
                   $scope.result = (_c) ? _c + "(来源缓存)" :
"刷新失败!";
               }
           });
    </script>
</body>
</html>

①首先、创建一项名为"cache"的服务,该服务返回一个自定义名称为"mycache"的缓存实例;并将缓存实例的最大容量定义为3次,用于控制器的注入。
②在构建控制器代码时,注入cache服务,并将配置对象中的"cache"属性值设置为cache服务对象,实现缓存实例传递的功能。
③当HTTP请求成功后,不仅在页面中显示返回的数据,而且还调用缓存对象中put方法将服务端返回的数据添加到键名为"c"的缓存中。

需要说明的是,无论是默认还是自定义的缓存对象,他们仅保存在一次请求中,没有保存在内存或文件中,因此,一旦刷新了页面,原来的缓存都将丢失。
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Angular,可以使用FormGroup和FormControl来管理表单数据,也可以通过使用本地存储(localStorage)来缓存表单数据。 以下是一个简单的例子,可以将表单数据存储在本地存储: 1. 在表单组件,定义一个FormGroup对象,并将其初始化为存储在本地存储的值(如果存在): ``` import { Component } from '@angular/core'; import { FormGroup, FormControl } from '@angular/forms'; @Component({ selector: 'app-form', templateUrl: './form.component.html', styleUrls: ['./form.component.css'] }) export class FormComponent { form: FormGroup; constructor() { this.form = new FormGroup({ name: new FormControl(localStorage.getItem('name')), email: new FormControl(localStorage.getItem('email')), phone: new FormControl(localStorage.getItem('phone')) }); } onSubmit() { // Save form data to local storage localStorage.setItem('name', this.form.value.name); localStorage.setItem('email', this.form.value.email); localStorage.setItem('phone', this.form.value.phone); // Submit form data to server // ... } } ``` 2. 在表单提交时,将表单数据存储在本地存储: ``` onSubmit() { // Save form data to local storage localStorage.setItem('name', this.form.value.name); localStorage.setItem('email', this.form.value.email); localStorage.setItem('phone', this.form.value.phone); // Submit form data to server // ... } ``` 3. 在表单组件添加一个ngOnDestroy钩子函数,以确保在组件销毁时清除本地存储的表单数据: ``` import { Component, OnDestroy } from '@angular/core'; import { FormGroup, FormControl } from '@angular/forms'; @Component({ selector: 'app-form', templateUrl: './form.component.html', styleUrls: ['./form.component.css'] }) export class FormComponent implements OnDestroy { form: FormGroup; constructor() { this.form = new FormGroup({ name: new FormControl(localStorage.getItem('name')), email: new FormControl(localStorage.getItem('email')), phone: new FormControl(localStorage.getItem('phone')) }); } onSubmit() { // Save form data to local storage localStorage.setItem('name', this.form.value.name); localStorage.setItem('email', this.form.value.email); localStorage.setItem('phone', this.form.value.phone); // Submit form data to server // ... } ngOnDestroy() { // Clear form data from local storage localStorage.removeItem('name'); localStorage.removeItem('email'); localStorage.removeItem('phone'); } } ``` 这样,当用户重新访问该页面时,表单数据将从本地存储自动填充。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值