1

Tengo un problema al compilar la aplicación, para producción, en local funciona bien. Tengo el siguiente componente:

  import { Component} from '@angular/core';
  import { ActivatedRoute } from '@angular/router';
  import * as StocksAPI from './../simbolos/earnings';
  import { IexEarningsService } from './../services/iex-earnings.service';


 @Component({
   selector: 'app-symbol-detail',
   templateUrl: './symbol-detail.component.html',
   styleUrls: ['./symbol-detail.component.css']
 })

 export class SymbolDetailComponent {


dataEarnings: Array<StocksAPI.EarningsResponse> = [];
constructor(

private route: ActivatedRoute,
private _servicioIEX: IexEarningsService) {

this.getEarnings();

}
getEarnings() {

this.route.params.subscribe(result => {
this._servicioIEX.obtenerDatosEarnings(result['symbol']).subscribe((res)                     => {
this.dataEarnings = res

  })
})
}

Con la siguiente interface:

export interface Earning {
  actualEPS: number
  consensusEPS: number
  estimatedEPS: number
  announceTime: string
  numberOfEstimates: number
  EPSSurpriseDollar: number
  EPSReportDate: string
  fiscalPeriod: string
  fiscalEndDate: string
  yearAgo: number
  yearAgoChangePercent: number
  estimatedChangePercent: number
  symbolId: number
 }

 export interface EarningsResponse {
  symbol: string
  earnings: [Earning]
 }

He creado un servicio con Observable que tiene el siguiente código:

import { Injectable } from '@angular/core';
import { HttpClient} from '@angular/common/http';
import { Observable} from 'rxjs';
import * as StocksAPI from './../simbolos/earnings';

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

private url = "https://api.iextrading.com/1.0/stock/"

private earnings = "/earnings"

constructor(private http: HttpClient) {
console.log('Servicio earnings funcionando!')
}

obtenerDatosEarnings(symbol): Observable<StocksAPI.EarningsResponse[]> {
 return this.http
  .get<StocksAPI.EarningsResponse[]>(this.url + symbol + this.earnings)

}
}

Y en el html tengo la siguiente tabla:

  <table class="table table-hover table-sm">
   <thead>
    <th>Fiscal Period</th>
    <th>Actual EPS</th>
    <th>EPS Report Date</th>
    <th>Fiscal End Date</th>
  </thead>
  <tbody class="detalle" *ngFor="let item of dataEarnings.earnings;let k=index">
    <th>{{dataEarnings.earnings[k].fiscalPeriod}}</th>
    <td>{{dataEarnings.earnings[k].actualEPS}}</td>
    <td>{{dataEarnings.earnings[k].EPSReportDate}}</td>
    <td>{{dataEarnings.earnings[k].fiscalEndDate}}</td>
  </tbody>
 </table>

Al utilizar ng build --prod genera el siguiente Error:

ERROR in src\app\symbol-detail\symbol-detail.component.html(20,28): : Property 'earnings' does not exist on type 'EarningsResponse[]'.

En local funciona bien, pero no me deja compilar el proyecto, y otra pregunta es, ¿Es la forma correcta de utilizar el servicio con Observable?

Muchas Gracias.

1

2 respuestas 2

2

El mensaje de error es bastante descriptivo:

Property 'earnings' does not exist on type 'EarningsResponse[]'.

Que significa que la propiedad earnings no está presente en un objeto de la clase EarningsResponse[].

La clave está en la clase: EarningsResponse[] es lo mismo que Array<EarningsResponse>. Es decir, TS te está diciendo que la clase Array, sean los items guardados del tipo que sean, no tiene una propiedad earnings.

Por otro lado tiene que una llamada GET a https://api.iextrading.com/1.0/stock/MSFT/earnings devuelve algo como:

{
    "symbol": "MSFT",
    "earnings": [{
        "actualEPS": 1.13,
        "consensusEPS": 1.07,
        "estimatedEPS": 1.07,
        "announceTime": "AMC",
        "numberOfEstimates": 14,
        "EPSSurpriseDollar": 0.06,
        "EPSReportDate": "2018-07-19",
        "fiscalPeriod": "Q4 2018",
        "fiscalEndDate": "2018-06-30",
        "yearAgo": 0.98,
        "yearAgoChangePercent": 0.15306122448979584,
        "estimatedChangePercent": 0.09183673469387764,
        "symbolId": 4563
    }, {
        "actualEPS": 0.95,
        "consensusEPS": 0.85,
        "estimatedEPS": 0.85,
        "announceTime": "AMC",
        "numberOfEstimates": 14,
        "EPSSurpriseDollar": 0.1,
        "EPSReportDate": "2018-04-26",
        "fiscalPeriod": "Q3 2018",
        "fiscalEndDate": "2018-03-31",
        "yearAgo": 0.73,
        "yearAgoChangePercent": 0.3013698630136986,
        "estimatedChangePercent": 0.1643835616438356,
        "symbolId": 4563
    }, {
        "actualEPS": 0.96,
        "consensusEPS": 0.86,
        "estimatedEPS": 0.86,
        "announceTime": "AMC",
        "numberOfEstimates": 14,
        "EPSSurpriseDollar": 0.1,
        "EPSReportDate": "2018-01-31",
        "fiscalPeriod": "Q2 2018",
        "fiscalEndDate": "2017-12-31",
        "yearAgo": 0.83,
        "yearAgoChangePercent": 0.1566265060240964,
        "estimatedChangePercent": 0.036144578313253045,
        "symbolId": 4563
    }, {
        "actualEPS": 0.84,
        "consensusEPS": 0.72,
        "estimatedEPS": 0.72,
        "announceTime": "AMC",
        "numberOfEstimates": 14,
        "EPSSurpriseDollar": 0.12,
        "EPSReportDate": "2017-10-26",
        "fiscalPeriod": "Q1 2018",
        "fiscalEndDate": "2017-09-30",
        "yearAgo": 0.76,
        "yearAgoChangePercent": 0.1052631578947368,
        "estimatedChangePercent": -0.05263157894736847,
        "symbolId": 4563
    }]
}

que no es un array es un simple objeto.

Es decir, en local te funciona porque el compilador no es tan estricto e ignora el tipado, pero la compilación para producción te dice que lo que intentas está mal.

La solución es muy simple: tu método en el Service debería devolver un EarningsResponse y no un EarningsResponse[], simplemente elimina los corchetes.

2

Typescript por ser un lenguaje fuertemente tipado necesita que las variables esten definidas con el tipo de datos que espera, en tu caso estas definiendo un array cuando es un solo objeto. Tambien tienes un detalle en la interfaz, la cambiaria por Model ya que la tienes para definir un modelo en base a una interfaz.

El codigo.

 export class EarningsResponse {
  symbol: string
  earnings: [Earning]
 }

Cambia mi interfaz por Class(Seria un Modelo ahora)

Cambia el servicio de tipo EarningResponse y no EarningResponse[]

obtenerDatosEarnings(symbol): Observable<StocksAPI.EarningsResponse> {
 return this.http
  .get<StocksAPI.EarningsResponse>(this.url + symbol + this.earnings)
}

Cambio mi componente a el dato que espera e instancialo , en caso de que quiera usar sus valores por defecto

dataEarnings: StocksAPI.EarningsResponse = new StocksAPI.EarningsResponse(); 

Finalmente cambiaria la forma de vizualizarlo en el HTML

  <tbody class="detalle" *ngFor="let item of dataEarnings.earnings">
    <th>{{item.fiscalPeriod}}</th>
    <td>{{item.actualEPS}}</td>
    <td>{{item.EPSReportDate}}</td>
    <td>{{item.fiscalEndDate}}</td>
  </tbody>

Te invito a leer tambien una respuesta parecida a esta de el porque te devuelve undefined

1
  • ¡Cuidado con usar una clase donde deberías usar un interfaz! Una llamada AJAX te devolverá un objeto obtenido de un JSON que cumple con la interfaz, pero no pertenecerá a la clase y si usas instanceof te fallará. el 9 oct. 2018 a las 10:34

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.