将api数据存储并更新到本地存储中,以便快速预呈现页面

时间:2017-09-22 14:07:46

标签: angular api local-storage ng2-charts

我通过与asp.net核心集成的Angular 4 universal构建比特币图表。我从api端点(https://www.coindesk.com/api/)发出了http请求,它返回数据以显示图表。每次我重新加载页面时,图表显示总是延迟大约1-2秒,因为它从服务器提取数据。我想问其他解决方案来防止这种情况,主要目的是使图表快速预渲染与模板上的纯文本相同。因此,我考虑将api数据存储到本地存储中,因此重新加载页面会从本地存储中提取数据,从而实现快速呈现。有可能吗?

以下是我目前的代码:

historical-bpi.service.ts:

gradientLayer.colors = lineColors.map({$0.cgColor})

组件ts:

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';

@Injectable()
export class HistoricalBpiService {

  private JsonBaseUrl: string = 'https://api.coindesk.com/v1/bpi/';

  constructor(private http:Http) { }

  getBpiData(url: string){
    return this.http.get(this.JsonBaseUrl+url)
      .map(res => res.json());
  }
}

组件html:

import { Component, OnInit, Inject, PLATFORM_ID } from '@angular/core';
import { HistoricalBpiService } from '../../services/historical-bpi.service';
import { isPlatformBrowser, isPlatformServer } from '@angular/common';
import * as moment from 'moment';

@Component({
  selector: 'app-banner',
  templateUrl: './banner.component.html',
  styleUrls: ['./banner.component.scss']
})
export class BannerComponent implements OnInit {

  private isDataAvailable: boolean;

  // Define date options
  private today: string = moment().format('YYYY-MM-DD');
  private oneYearAgo: string = moment().subtract(1,'years').format('YYYY-MM-DD');
  private nineMonthsAgo: string = moment().subtract(9,'months').format('YYYY-MM-DD');

  private oneYearData: string = 'historical/close.json?start=' + this.oneYearAgo + '&end=' + this.today;
  private nineMonthsData: string = 'historical/close.json?start=' + this.nineMonthsAgo + '&end=' + this.today;      

  // API calls for the date options
  oneYear() {
    this.historicalBpiService.getBpiData(this.oneYearData)
      .subscribe(
        res => {
          this.lineChartData[0].data = Object.keys(res.bpi).map(function (key) { return res.bpi[key]; });
          this.lineChartLabels = Object.keys(res.bpi);
          this.isDataAvailable = true;
        }
      )
  }

  nineMonths() {
    this.historicalBpiService.getBpiData(this.nineMonthsData)
      .subscribe(
        res => {
          this.lineChartData[0].data = Object.keys(res.bpi).map(function (key) { return res.bpi[key]; });
          this.lineChartLabels = Object.keys(res.bpi);
        }
      )
  }      

  constructor(
    private historicalBpiService:HistoricalBpiService,
    @Inject(PLATFORM_ID) private platformId: Object
  ) {}

  // lineChart

  public lineChartData:any = [
    { data:[], label: 'BTC' }
  ];

  public lineChartLabels:Array<any> = [];

  public lineChartOptions:any = {
    responsive: true,
    maintainAspectRatio: false,
    layout: {
      padding: 0
    },        
    scales: {
      yAxes: [{
        display: false,
        scaleLabel: {
          display: false,
          labelString: 'USD'
        },            
        gridLines: {
          display: true,
          tickMarkLength: 0
        }
      }],
      xAxes: [{
        ticks: {
          display: false,
          mirror: true
        }          
      }]
    },
    elements: {
      point: {
        radius: 0
      },
      line: {
        tension: 0, // 0 disables bezier curves
      }
    },
    hover: {
      mode: 'label',
      intersect: false
    },
    tooltips: {
      mode: 'label',
      intersect: false,
      backgroundColor: 'rgb(95,22,21)'          
    }
  };
  public lineChartColors:Array<any> = [
    {
      backgroundColor: 'rgba(199,32,48,1)',
      //borderColor: 'rgb(95,22,21)',
      pointHoverBackgroundColor: 'rgba(218,208,163,1)',
      steppedLine: false
    }
  ];
  public lineChartLegend:boolean = false;
  public lineChartType:string = 'line';    

  // events
  public chartClicked(e:any):void {
    console.log(e);
  }

  public chartHovered(e:any):void {
    console.log(e);
  }

  ngOnInit(){
    if (isPlatformBrowser(this.platformId)) {
      // Default chart
      this.oneYear();
    }
  }
}

1 个答案:

答案 0 :(得分:0)

根据这篇文章What is the max size of localStorage values?,每个存储的限制为10Mb,值只能存储为字符串。

如果你监控你的应用程序并且调用是瓶颈(不是渲染或应用程序启动),我建议使用像PouchDB / CouchDB这样的东西来为你提供本地文档存储。 https://pouchdb.com/