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

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

这可能吗?


当前回答

由于AngularJS的工厂是单例的,你可以简单地存储http请求的结果,并在下次你的服务被注入到其他东西时检索它。

angular.module('myApp', ['ngResource']).factory('myService',
  function($resource) {
    var cache = false;
    return {
      query: function() {
        if(!cache) {
          cache = $resource('http://example.com/api').query();
        }
        return cache;
      }
    };
  }
);

其他回答

angularBlogServices.factory('BlogPost', ['$resource',
    function($resource) {
        return $resource("./Post/:id", {}, {
            get:    {method: 'GET',    cache: true,  isArray: false},
            save:   {method: 'POST',   cache: false, isArray: false},
            update: {method: 'PUT',    cache: false, isArray: false},
            delete: {method: 'DELETE', cache: false, isArray: false}
        });
    }]);

将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的结果,以便它可以用于对该方法的进一步请求。

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

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

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);
   });
}

由于AngularJS的工厂是单例的,你可以简单地存储http请求的结果,并在下次你的服务被注入到其他东西时检索它。

angular.module('myApp', ['ngResource']).factory('myService',
  function($resource) {
    var cache = false;
    return {
      query: function() {
        if(!cache) {
          cache = $resource('http://example.com/api').query();
        }
        return cache;
      }
    };
  }
);