如何将此API get()结果转换为JSON对象?

时间:2019-05-28 20:54:23

标签: json angular observable

API端点返回一个可观察值。当我尝试检索返回对象的任何属性时,表明该属性在类型{}上不存在

这是端点结果

{
  "base": "EUR",
  "date": "2018-04-08",
  "rates": {
    "CAD": 1.565,
    "CHF": 1.1798,
    "GBP": 0.87295,
    "SEK": 10.2983,
    "EUR": 1.092,
    "USD": 1.2234,
  }
}



service.ts

import { Injectable } from '@angular/core';
import { HttpClient, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import { ConvertResultModel } from './converter/convert-result-model';

@Injectable({
  providedIn: 'root'
})
export class ServiceProviderService {
  private baseUrl = 'https://api.exchangeratesapi.io/latest';
  constructor(private http: HttpClient) { }
  getLatest():Observable<ConvertResultModel>{
    return this.http.get<ConvertResultModel>(this.baseUrl);
  }
}



converter.component.ts

import { ServiceProviderService } from './../service-provider.service';
import { Component, OnInit } from '@angular/core';


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

  constructor(private serviceProvider: ServiceProviderService) { }
  private resultSet = {};
  ngOnInit()
  {
    this.serviceProvider.getLatest().subscribe(data => this.resultSet = data);
    console.log(this.resultSet.base);
  }
}



convert-result-model.ts

export interface ConvertResultModel {
  base: number;
  date: string;
  rates: any[];
}



src / app / converter / converter.component.ts(17,32)中的错误:错误TS2339:类型“ {}”上不存在属性“ base”。

1 个答案:

答案 0 :(得分:1)

所有有关打字稿中类型检查的内容。很好,但是有时您不想定义所有类型。

所以您可能要替换

private resultSet = {};

类似

private resultSet:any = {};
// or 
//private resultSet:any = null;

或定义一个类或接口,并将resultSet的类型设置为该类或接口。像这样:

public interface ResultSet{
  base: String;
  // etc
}

然后

private resultSet:ResultSet= {} as ResultSet;
// or 
//private resultSet:ResultSet= null;

但是我的建议是尝试使用打字稿的功能进行练习,这可以帮助您在编译时而不是运行时捕获一些错误