【问题标题】:How to cache XHR in Angular2 [duplicate]如何在Angular2中缓存XHR [重复]
【发布时间】:2016-08-26 06:30:17
【问题描述】:

我搜索了如何在Angular2中缓存XHR,发现使用share()方法。但是我创建的服务并没有达到我的预期。

// api_service.interface.ts
interface Api {}
@Injectable()
export class ApiService {
  private caches: { [url: string]: Observable<Api> } = {};

  constructor(private http: Http) {}

  fetch(req: Request): Observable<Api> {
    return this.http.request(req).map((res) => res.json());
  }
  get(url: string): Observable<Api> {
    // Return cached data
    if (url in this.caches) return this.caches[url];

    let req = {
      method: RequestMethod.Get,
      url: url,
    }

    // Store observable object using share() method
    return this.caches[url] = this.fetch(new Request(req)).share();
  }
}

// demo.component.ts
@Component({ ... })
export class DemoComponent {
  public data;

  constructor(private api: ApiService) {
    this.api.get('/test.json').subscribe((data) => this.data = data);
  }
}

// boot.ts
import { ... } from ...
bootstrap(RouterComponent, [ApiService, ...]);

我错过了什么? (当然要导入需要的类和接口)

【问题讨论】:

    标签: typescript angular


    【解决方案1】:

    为此,您需要利用 do 运算符:

    getData() {
      if (this.cachedData) {
        return Observable.of(this.cachedData);
      } else {
        return this.http.get(...).map(...)
            .do(data => {
              this.cachedData = data;
            })
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2018-03-23
      • 2020-03-02
      • 2015-08-15
      • 1970-01-01
      • 2011-04-02
      • 1970-01-01
      • 1970-01-01
      • 2013-10-20
      • 2012-01-28
      相关资源
      最近更新 更多