user1298426
user1298426

Reputation: 3717

How to create a graphql query with arguments in angular using apollo client library

I am working on apollo client library for integrating graphql with angular. I am able to do simple queries like findAll without any arguments

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

I am able to fetch result with this query using watchQuery

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

but I am not able to create a complex query with arguments like

{
  allDataWithFilter(
    date: {from: "2010-01-16T10:20:10", to: "2019-01-16T11:16:10"}, 
    name: "ABC" {
    allDataWithFilter {
      id
      fromDate
      toDate
      name
            ...      
    }
    totalPages
    totalElements
  }
}

How do I pass date and other arguments in the query?

Upvotes: 0

Views: 4862

Answers (2)

Manzur Khan
Manzur Khan

Reputation: 2486

You should read your schema in order to understand what the server needs and should pass the appropriate data with types. I hope it will be something like this in your case.

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

When you are calling this query just pass this data in variables like this

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

Upvotes: 2

robbannn
robbannn

Reputation: 5013

I have defined one of my queries that takes an argument like this:

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

($uid: String!) allows me to pass in an argument to the query. Calling the query:

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

Upvotes: 1

Related Questions