如何使用Apollo客户端库创建带有angular参数的graphql查询

时间:2019-01-18 10:09:26

标签: angular apollo-client

我正在使用apollo客户端库来集成graphql和angular。 我可以进行简单的查询,例如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
  }
}

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

2 个答案:

答案 0 :(得分:0)

我已经定义了一个查询,该查询采用这样的参数:

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

答案 1 :(得分:0)

您应该阅读架构以了解服务器的需求,并应将适当的数据与类型一起传递。 希望您遇到这种情况。

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