首页 > 解决方案 > 如何使用 apollo 客户端库创建带有角度参数的 graphql 查询

问题描述

我正在开发用于将 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
  }
}

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

标签: angularapollo-client

解决方案


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

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

推荐阅读