Home > Mobile >  Argument of type 'Object' is not assignable to parameter of type 'Interface'
Argument of type 'Object' is not assignable to parameter of type 'Interface'

Time:12-06

getHeaderCurrencies(): currencyInterface[]{
    let array: **any**[] = [];
    this.http
      .get(`${this.url}?from=${this.currency1}&to=${this.baseCurrency}&amount=1&places=2`)
      .subscribe(res => array.push(res))
    this.http
      .get(`${this.url}?from=${this.currency2}&to=${this.baseCurrency}&amount=1&places=2`)
      .subscribe(res => array.push(res))
    return array
  }

When i try to change type of elements in array from any to currencyInterface i face the problem from the title on each "res". What should i do?

CodePudding user response:

You can pass a generic type to the get method of http.

The result:

getHeaderCurrencies(): currencyInterface[] {
    const array: currencyInterface[] = [];

    this.http
      .get<currencyInterface>(`${this.url}?from=${this.currency1}&to=${this.baseCurrency}&amount=1&places=2`)
      .subscribe(res => array.push(res))
    this.http
      .get<currencyInterface>(`${this.url}?from=${this.currency2}&to=${this.baseCurrency}&amount=1&places=2`)
      .subscribe(res => array.push(res))

    return array
}

Also, since you're making http calls you can just parse them as promises with Observable.prototype.toPromise() method and that would become:

async getHeaderCurrencies(): Promise<currencyInterface[]> {
    const c1 = this.http
      .get<currencyInterface>(`${this.url}?from=${this.currency1}&to=${this.baseCurrency}&amount=1&places=2`)
      .toPromise()
    const c2 = this.http
      .get<currencyInterface>(`${this.url}?from=${this.currency2}&to=${this.baseCurrency}&amount=1&places=2`)
      .toPromise()

    return Promise.all([c1, c2])
}
  • Related