Angular 7:一键加载api(需要两次单击)

时间:2018-12-16 09:52:06

标签: angular api

我希望我的英语能帮助您理解我的问题。

我正在尝试从API加载数据,但是我需要单击2次才能查看数据。

似乎我需要加载两次数据才能更新它 第一次单击时,我得到了数据,但没有更新。

我为'prefetch'创建了一个事件(mouseenter),但是这种解决方案太可怕了。

有帮助吗?

谢谢

HTML(非常简单的文件)

<form  [formGroup]="getRates"><div class="form-group">
        <div class="row">
          <div class="col-md-6">
              <select
                class="form-control"
                name="bases"
                formControlName="bases"
                placeholder="Select Currency"
               ><option *ngFor="let item of bases" [value]="item.curr">{{item.curr}}</option>
              </select>
          </div>
          <div class="col-md-6">
              <input
                name="date"
                type="text"
                class="form-control"
                placeholder="Datepicker"
                formControlName="date"
                bsDatepicker>
          </div>
        </div></div><button class="btn btn-primary" type="submit" (click)="showConfig()" (mouseenter)="showConfig()">Get rates</button></form>

TS(在这里设置表格的值)

     import { Component, OnInit} from '@angular/core';
import{ ConfigService, Config } from './config.service';
import { FormGroup, FormControl } from '@angular/forms';
    @Component({
      selector: 'app-form',
      templateUrl: './form.component.html',
      styleUrls: ['./form.component.css']
    })
    export class FormComponent implements OnInit {
      bases: any[];
      date: any;
      day: number;
      mounth: number;
      year: number;
      config: Config;
      getRates: FormGroup;
      currency: string;
      i: number;
      error: any;
      constructor(private configService: ConfigService) { }
      ngOnInit() {
        this.getRates = new FormGroup({
          'date': new FormControl(),
           'bases': new FormControl(),
         });
        this.bases = this.configService.tableData;
      }
      public showConfig() {
        if (this.getRates.value.bases) {
          this.currency = this.getRates.get('bases').value;
        }
        if (this.getRates.value.date) {
          this.day = this.getRates.get('date').value.getDate();
          this.mounth = this.getRates.get('date').value.getMonth() + 1;
          this.year = this.getRates.get('date').value.getFullYear();
        }
        this.date = `${this.year}-${this.mounth}-${this.day}` ;
        console.log(this.currency, this.getRates.value.date);
        this.configService.configUrl = `https://api.exchangeratesapi.io/${this.date}?base=${this.currency}`;
        this.configService.getConfig()
            .subscribe(
              (data: Config) => this.config = { ...data },
              error => this.error = error
            );
            this.i = 0;
              for (const value of this.bases) {
                if (this.config) {
                this.i++;
                this.configService.tableData[this.i - 1].buy = this.config.rates[value.curr] - (this.config.rates[value.curr] / 100 * 5);
                this.configService.tableData[this.i - 1].sell = this.config.rates[value.curr] + (this.config.rates[value.curr] / 100 * 5);
                }
              }
      }preFetchData() {
        this.showConfig();
      }
    }

SERVICE TS(在这里我获得了API数据)

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



export interface Config {
  base: string;
  date: string;
  rates: number[];

}

@Injectable({
  providedIn: 'root'
})
export class ConfigService {

  config: Config;
  rates = ['EUR', 'USD', 'GBP', 'AUD', 'CAD', 'JPY'];
  tableData = [
    {'curr': 'GBP', 'buy': 1, 'sell': 1},
    {'curr': 'EUR', 'buy': 1, 'sell': 1},
    {'curr': 'USD', 'buy': 1, 'sell': 1},
    {'curr': 'AUD', 'buy': 1, 'sell': 1},
    {'curr': 'CAD', 'buy': 1, 'sell': 1},
    {'curr': 'JPY', 'buy': 1, 'sell': 1},
  ];
  constructor(private http: HttpClient) {
   }

  configUrl = '';

  getConfig() {
    return this.http.get<Config>(this.configUrl);
  }
}

控制台日志

enter image description here

1 个答案:

答案 0 :(得分:0)

默认情况下,使用HttpClient可以实现承诺,所以我添加()=> this.preFetchData(),然后将代码移至另一个函数中。

此处是代码

const Link = ({ active, children, onClick }) => {
  if (active) {
    return <span>{children}</span>
  }

  return (
    <a
      href=""
      onClick={e => {
        e.preventDefault()
        onClick()
      }}
    >
      {children}
    </a>
  )
}

// ...
export default connect(mapState, mapDispatch)(Link)