我希望能够创建一个自定义AngularJS服务,当它的数据对象为空时,它会发出一个HTTP“Get”请求,并在成功时填充数据对象。
下次调用此服务时,我希望绕过再次发出HTTP请求的开销,而是返回缓存的数据对象。
这可能吗?
我希望能够创建一个自定义AngularJS服务,当它的数据对象为空时,它会发出一个HTTP“Get”请求,并在成功时填充数据对象。
下次调用此服务时,我希望绕过再次发出HTTP请求的开销,而是返回缓存的数据对象。
这可能吗?
当前回答
在当前的稳定版本(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
});
});
一个缺点是键名也是自动设置的,这可能会使清除它们变得棘手。希望他们能以某种方式添加键名。
其他回答
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);
});
}
在当前的稳定版本(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;
}])
在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的结果,以便它可以用于对该方法的进一步请求。
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。