Z
Z
zlodiak2019-07-13 13:22:24
Angular
zlodiak, 2019-07-13 13:22:24

Why doesn't the property exist on the object?

I wrote a helloWorld level example that gets the currency rate, but the example doesn't run. The following error message is displayed in the console:

ERROR in src/app/components/exchange-rates/exchange-rates.component.ts(33,73): error TS2339: Property 'rates' does not exist on type '{}'.

Here is the component code:
import { Component, OnInit } from '@angular/core';
import { Apollo } from 'apollo-angular';
import gql from 'graphql-tag';
import { Observable } from 'rxjs';
import { shareReplay, map } from 'rxjs/operators';


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

  rates$: Observable<any[]>;
  loading$: Observable<boolean>;
  errors$: Observable<any>;

  constructor(private apollo: Apollo) { }

  ngOnInit() {
    const source$ = this.apollo.query({
      query: gql`
        {
          rates(currency: "USD") {
            currency
            rate
          }
        }
      `
    }).pipe(shareReplay(1));

    this.rates$ = source$.pipe(map(result => result.data && result.data.rates));
    this.loading$ = source$.pipe(map(result => result.loading));
    this.errors$ = source$.pipe(map(result => result.errors));
  }

}

The problem is that in the official appolo documentation there is a link to a working example . And my code completely repeats this example (even package.json is the same)
Please help me understand how to fix my script and in general what is the essence of the error.
I tried putting in setTimeout block:
this.rates$ = source$.pipe(map(result => result.data && result.data.rates));
    this.loading$ = source$.pipe(map(result => result.loading));
    this.errors$ = source$.pipe(map(result => result.errors));

but didn't help.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Shvets, 2019-07-13
@zlodiak

result.data['rates']
And generally it is necessary to describe as though types. Ts thinks that your result.data is an empty object.
setTimeout has nothing to do with it, it's a typescript compilation error.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question