问题描述
我有一个通过HTTP服务获取数据并返回可观察对象的服务.
I have a service that fetches data via the HTTP service and returns an observable object.
第一次调用后,我想在服务内部缓存结果,一旦新组件尝试获取数据,它将从缓存的结果中获取数据.
After the first call I would like to cache the result internally in the service, and once a new component will try to get the data it will take it from the cached result.
有一个简单的解决方案吗?
Is there a simple solution for this?
推荐答案
如果您倾向于使用可观察变量作为共享数据的方法,则可以采用以下方法:
If you lean into observables as a means of sharing data, you can adopt the following approach:
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable, ReplaySubject } from 'rxjs';
@Injectable()
export class CachedService {
data$: Observable<Response> = this.dataSubject.asObservable();
private dataSubject = new ReplaySubject<Response>(1);
constructor(private http: Http) { }
fetch() {
this.http.get(...).subscribe(res => this.dataSubject.next(res));
}
}
这将在调用fetch
方法时进行HTTP调用,并且service.data$
的所有订阅者都将从ReplaySubject
获得响应.在重放早期值时,在 之后通过HTTP调用解析加入的所有订阅者仍将获得先前的响应.
This will make an HTTP call when the fetch
method is called, and any subscribers to service.data$
will get the response from the ReplaySubject
. As it replays earlier values, any subscribers who join after the HTTP call resolves will still get the previous response.
如果要触发更新,只需调用service.fetch()
以启动新的HTTP调用,一旦新响应到达,所有订户将被更新.
If you want to trigger an update, you can just call service.fetch()
to kick off a new HTTP call and all subscribers will be updated once the new response arrives.
您的组件将如下所示:
@Component({ ... })
export class SomeComponent implements OnInit {
constructor(private service: CachedService) { }
ngOnInit() {
this.service.fetch();
this.service.data$.subscribe(...);
}
}
我最近为同事写了一篇有关此方法的博客文章: http://blog.jonrshar.pe/2017/Apr/09/async-angular-data.html
I've recently written a blog article on this approach for my colleagues: http://blog.jonrshar.pe/2017/Apr/09/async-angular-data.html
这篇关于Angular 2缓存可观察到的http结果数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!