Apollo-Angular 查询 return 奇怪的行为

Apollo-Angular query return weird behaviour

我正在尝试将 Angular 与 GraphQL 后端连接。

然而,当 angular-apollo 从 GraphQL 请求数据时,数据被正确发送,但是当我想要访问它时,它 returns undefined.

在下面的代码中,updateItems() 正常工作,但 getItems() 不正常。

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
    });
  }
}

getItem(name) 中,console.log(result.data) 调用在控制台中显示:

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

这是正确的,但是当我尝试记录 itemhistory 时,它显示 undefined。 我也无法访问 result.data.item,因为它不存在。

有人知道问题出在哪里吗?我感谢每一个答案。

我已经解决了问题,但解决方案并不完美。 我需要调用 result?.data?.item.

而不是 result.data.item

新方法是:

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);
      })
}