Angular 2缓存可观察的http结果数据 [英] Angular 2 cache observable http result data

查看:17
本文介绍了Angular 2缓存可观察的http结果数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个通过 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?

推荐答案

如果您倾向于将 observables 作为共享数据的一种方式,您可以采用以下方法:

If you lean into observables as a means of sharing data, you can adopt the following approach:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

import { Observable, ReplaySubject } from 'rxjs';

import { SomeModel } from 'path/to/it';

@Injectable({
  providedIn: 'root'
})
export class CachedService {
 
  private dataSubject = new ReplaySubject<SomeModel>(1);
  
  data$: Observable<SomeModel> = this.dataSubject.asObservable();

  constructor(private http: HttpClient) { }

  fetch() {
    this.http.get<SomeModel>(...).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 OnDestroy, OnInit {

  private subscription?: Subscription;

  constructor(private service: CachedService) { }

  ngOnInit() {
    this.service.fetch();
    this.subscription = this.service.data$.subscribe(...);
  }

  ngOnDestroy() {
    if (this.subscription) {
      this.subscription.unsubscribe();
    }
  }
}

我最近为我的同事写了一篇关于这种方法的博客文章: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结果数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆