首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Apollo-Angular查询返回奇怪的行为

Apollo-Angular查询返回奇怪的行为
EN

Stack Overflow用户
提问于 2021-03-15 14:34:44
回答 1查看 168关注 0票数 1

我正在尝试连接一个GraphQL后端的角度。

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

在下面的代码中,updateItems()运行正常,但getItems()运行正常。

代码语言:javascript
复制
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)调用在控制台中显示:

代码语言:javascript
复制
{item: {…}}
  item:
    currency: "€"
    history: (2287) [{…}, …]
    __typename: "Itemhistory"
    __proto__: Object
  __proto__: Object

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

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-03-15 18:33:01

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

新方法是:

代码语言:javascript
复制
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);
      })
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66633310

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档