【问题标题】:How to create a graphql query with arguments in angular using apollo client library如何使用 apollo 客户端库创建带有角度参数的 graphql 查询
【发布时间】:2019-06-12 14:03:10
【问题描述】:

我正在开发用于将 graphql 与 angular 集成的 apollo 客户端库。 我可以在没有任何参数的情况下执行 findAll 之类的简单查询

const allData = 
        gql`
        query allData {
          allData {
            id
            fromDate
            toDate
            name
            ...
          }
        }
      `

我可以使用 watchQuery 获取此查询的结果

this.data = this.apollo.watchQuery<Query>({query: allData}).valueChanges
      .pipe(
        map(result => result.data.allData)
      );

但我无法使用诸如

之类的参数创建复杂查询
{
  allDataWithFilter(
    date: {from: "2010-01-16T10:20:10", to: "2019-01-16T11:16:10"}, 
    name: "ABC" {
    allDataWithFilter {
      id
      fromDate
      toDate
      name
            ...      
    }
    totalPages
    totalElements
  }
}

如何在查询中传递日期和其他参数?

【问题讨论】:

    标签: angular apollo-client


    【解决方案1】:

    我已经定义了一个接受如下参数的查询:

    const ListCalculations = gql`
        query ListCalculations($uid: String!){
            listCalculations(uid: $uid){
                details {
                    customer
                    part
                }
                selectedUnit {
                    imgSrc
                }
            }
        }
    `;
    

    ($uid: String!) 允许我将参数传递给查询。 调用查询:

    const queryObj:QueryObject = {
        query: ListCalculations,
        variables: { uid: this.authService.cognitoUser.getUsername() },
        fetchPolicy: 'cache-and-network'
    };
    
    let obs = client.watchQuery(queryObj);
    obs.subscribe(result => console.log(result));
    

    【讨论】:

    • 我可以发送带有字符串的查询,但不能发送带有 from 和 to 的自定义对象日期。您能告诉我您的代码将如何处理这些字段吗?
    • 我建议您为此打开一个单独的问题。这个问题是关于将参数传递给查询。
    【解决方案2】:

    您应该阅读您的架构以了解服务器需要什么,并且应该使用类型传递适当的数据。 我希望你的情况是这样的。

    {
      allDataWithFilter(
        date: {$from: DateTime, $to: DateTime}, 
        name: String {
        allDataWithFilter(from: $from, to: $to) {
          id
          fromDate
          toDate
          name
                ...      
        }
        totalPages
        totalElements
      }
    }
    

    当您调用此查询时,只需将这些数据传递到像这样的变量中

    this.apollo.query({
      query: YourQuery,
      variables: {
       from: new Date(),
       to: someDate
    }
    })
    

    【讨论】:

    猜你喜欢
    • 2020-11-24
    • 2021-04-03
    • 2021-04-02
    • 2017-12-20
    • 2016-08-31
    • 2019-01-18
    • 2018-08-25
    • 1970-01-01
    • 2019-07-26
    相关资源
    最近更新 更多