Search code examples
angulargraphqlapollo-angular

Apollo-Angular query return weird behaviour


I am trying to connect Angular with a GraphQL backend.

However, when angular-apollo requests data from GraphQL, the data is being sent correctly but when I want to access it, it returns undefined.

In the following code, updateItems() is working correctly but getItems() not.

import { EventEmitter, Injectable } from '@angular/core';
import { Apollo } from 'apollo-angular';
import gql from 'graphql-tag';

const GET_ITEMS = gql`
  { 
    items(limit: 1) {
      name
      rank
    }
  }
`;

const GET_ITEM = gql`
query Item($name: String!) {
  item(name: $name) {
    currency
    history {
      timestamp
      price
      volume
    }
  }
}
`;

type ItemType = {
    name: string,
    rank: number
}

type ItemhistoryType = {
    name: string,
    currency: string,
    history: {
        timestamp: number,
        price: number,
        volume: number
    }[]
}

type Query = {
  items: ItemType[];
}

type ItemQuery = {
  itemhistory: ItemhistoryType;
}

@Injectable()
export class ItemsService {
  items: ItemType[] = [];
  itemStatus = new EventEmitter<ItemType[]>();
  itemhistories: ItemhistoryType[] = [];
  itemhistoryStatus = new EventEmitter<ItemhistoryType>();

  constructor(private apollo: Apollo) {
    this.updateItems();
  }

  getItems() {
    return this.items.slice();
  }

  updateItems() {
    this.apollo.query<Query>({
      query: GET_ITEMS
    }).subscribe(result => {
      this.items = result.data.items as ItemType[];
      console.log(this.items);
      this.itemStatus.emit(this.items.slice());
    });
  }

  getItem(name: string) {
    console.log(name);
    this.apollo.query<ItemQuery>({
      query: GET_ITEM, 
      variables: { name: name }
    }).subscribe(result => {
      console.log(result.data); // shows data correctly
      let itemhistory = result.data.itemhistory as ItemhistoryType;
      console.log(itemhistory); // -> undefined
    });
  }
}

In getItem(name), the console.log(result.data) call shows this in the console:

{item: {…}}
  item:
    currency: "€"
    history: (2287) [{…}, …]
    __typename: "Itemhistory"
    __proto__: Object
  __proto__: Object

which is correct but when I try to log itemhistory it shows undefined. Also I can't access result.data.item because it does not exist.

Does anyone know what the problem is? I am thankful for every answer.


Solution

  • I have fixed the issue but the solution is not perfect. Instead of result.data.item I need to call result?.data?.item.

    The new method is:

    getItem(name: string) {
        this.apollo.query({
          query: GET_ITEM,
          variables: {
            name: name
          }
        })
          .subscribe((result: any) => {
            const history = result?.data?.item as ItemhistoryType;
            this.itemhistories.push(history);
            this.itemhistoryStatus.emit(history);
          })
    }