如何在角度5中缓存http请求?

时间:2018-04-30 17:13:17

标签: angular typescript

我已经在Angular 5应用程序中实现了缓存HTTP请求。但是,我的问题是我编写的代码将首先从api说“ API1 ”中保存来自First Http的数据,之后它将从存储的变量中获取数据,即国家/地区。但如果我使用不同的 API2 再次调用此服务,则它将从国家/地区获取值。

我的组件代码:

import { Component, OnInit } from '@angular/core';
import { CacheService } from '../cache.service';

 @Component({
 selector: 'app-caching',
 templateUrl: './caching.component.html',
 styleUrls: ['./caching.component.css']
})
export class CachingComponent implements OnInit {
constructor(private cacheService:CacheService){}
countries;
ngOnInit() {
  this.cacheService.get()
  .subscribe(res => {
    this.countries = res;
  });
 }
}

我的服务代码:

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

@Injectable()
export class CacheService {
  countries;

  constructor(private http:HttpClient) {}

  public get(): Observable<any> {
    if(this.countries != null) {
      console.log("Fetching Data From Cache!!!",this.countries);
      return Observable.of(this.countries);
    } 
    else {
      console.log("Fetching Data From Hit!!!"); 
      return this.http.get('https://jsonplaceholder.typicode.com/posts', {})
        .map((data) => {
          console.log(data);
          this.countries = data;
        })
        .publishReplay(1)
        .refCount();
    }
  }
}

我希望单独缓存不同的API命中。

0 个答案:

没有答案
相关问题