我希望能够创建一个自定义AngularJS服务,当它的数据对象为空时,它会发出一个HTTP“Get”请求,并在成功时填充数据对象。

下次调用此服务时,我希望绕过再次发出HTTP请求的开销,而是返回缓存的数据对象。

这可能吗?


当前回答

我想现在有一个更简单的方法。这将为所有$http请求($resource继承的)启用基本缓存:

 var app = angular.module('myApp',[])
      .config(['$httpProvider', function ($httpProvider) {
            // enable http caching
           $httpProvider.defaults.cache = true;
      }])

其他回答

在Angular 8中,我们可以这样做:

import { Injectable } from '@angular/core';
import { YourModel} from '../models/<yourModel>.model';
import { UserService } from './user.service';
import { Observable, of } from 'rxjs';
import { map, catchError } from 'rxjs/operators';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})

export class GlobalDataService {

  private me: <YourModel>;

  private meObservable: Observable<User>;

  constructor(private yourModalService: <yourModalService>, private http: HttpClient) {

  }

  ngOnInit() {

  }


  getYourModel(): Observable<YourModel> {

    if (this.me) {
      return of(this.me);
    } else if (this.meObservable) {
      return this.meObservable;
    }
    else {
      this.meObservable = this.yourModalService.getCall<yourModel>() // Your http call
      .pipe(
        map(data => {
          this.me = data;
          return data;
        })
      );
      return this.meObservable;
    }
  }
}

你可以这样调用它:

this.globalDataService.getYourModel().subscribe(yourModel => {


});

上面的代码将在第一次调用时缓存远程API的结果,以便它可以用于对该方法的进一步请求。

在当前的稳定版本(1.0.6)中,一种更简单的方法需要更少的代码。

设置好模块后,添加一个工厂:

var app = angular.module('myApp', []);
// Configure routes and controllers and views associated with them.
app.config(function ($routeProvider) {
    // route setups
});
app.factory('MyCache', function ($cacheFactory) {
    return $cacheFactory('myCache');
});

现在你可以把它传递到你的控制器:

app.controller('MyController', function ($scope, $http, MyCache) {
    $http.get('fileInThisCase.json', { cache: MyCache }).success(function (data) {
        // stuff with results
    });
});

一个缺点是键名也是自动设置的,这可能会使清除它们变得棘手。希望他们能以某种方式添加键名。

我想现在有一个更简单的方法。这将为所有$http请求($resource继承的)启用基本缓存:

 var app = angular.module('myApp',[])
      .config(['$httpProvider', function ($httpProvider) {
            // enable http caching
           $httpProvider.defaults.cache = true;
      }])

如果你喜欢$http的内置缓存,但想要更多的控制,请查看angular-cache库。您可以使用它来无缝地增加$http缓存,包括生存时间(time-to-live)、定期清除以及将缓存持久化到localStorage的选项,以便跨会话可用。

FWIW,它还提供了一些工具和模式,使您的缓存成为一种更动态的数据存储,您可以将其作为POJO进行交互,而不仅仅是默认的JSON字符串。目前还不能评论这个选项的效用。

(然后,在此基础上,相关库angular-data在某种程度上替代了$resource和/或Restangular,并依赖于angular-cache。)

Angular的$http有一个内置的缓存。根据文件:

cache - {boolean|Object} -使用$cacheFactory创建的布尔值或对象,用于启用或禁用HTTP响应的缓存。看到 $http缓存 信息。

布尔值

所以你可以在它的选项中将cache设置为true:

$http.get(url, { cache: true}).success(...);

或者,如果你喜欢配置类型的呼叫:

$http({ cache: true, url: url, method: 'GET'}).success(...);

缓存对象

你也可以使用缓存工厂:

var cache = $cacheFactory('myCache');

$http.get(url, { cache: cache })

你可以自己使用$cacheFactory来实现它(特别是在使用$resource时):

var cache = $cacheFactory('myCache');

var data = cache.get(someKey);

if (!data) {
   $http.get(url).success(function(result) {
      data = result;
      cache.put(someKey, data);
   });
}