Warm tip: This article is reproduced from stackoverflow.com, please click
angular apollo graphql apollo-client

Send 2 identical Graphql queries in one call but with different variables

发布于 2020-04-08 09:33:38

I have a search query which takes an variable and searches based on that.

On my home page I'd like to send this query 3 times with 3 different variables.

But if I do as above I can't get the results.

Here is the query:

const TOP_TEACHER_QUERY= gql`
    query topTeachers {
        searchBasicTeachersByRating(rating: 3) {
            id
            name
            title
        }
        searchBasicTeachersByRating(rating: 4) {
            id
            name
            title
            isNew
        }
    }
}

and this is the function

allQueries() {
    return this.apollo
        .watchQuery<any>({
            query: TOP_TEACHER_QUERY,
        })
        .valueChanges;
}

NOTE :

I have tried adding an interface and define the desired response data, but it has no effect

interface Response {
    searchBasicTeachersByRatingMedium: Student[];
    searchBasicTeachersByRatingHigh: Student[];
}

allQueries() {
    return this.apollo
        .watchQuery<any>({
            query: TOP_TEACHER_QUERY,
        })
        .valueChanges;
}

THE DATA IS ONLY CONTAINING A LIST NAMED AFTER THE QUERY (searchBasicTeachersByRating)

I have tried the following query in graphql playground and it returns 2 arrays but in Angular I can only get one

As a work around I created new queries at back-end, or sent 2 different queries.

But I want a solution for this approach.

Thanks in advance

Questioner
Farhad
Viewed
53
Daniel Rearden 2020-02-01 12:41

When a selection set includes the same field multiple times, you need to utilize aliases for the duplicate fields:

searchBasicTeachersByRatingMedium: searchBasicTeachersByRating(rating: 3) {
  id
  name
  title
}
searchBasicTeachersByRatingHigh: searchBasicTeachersByRating(rating: 4) {
  id
  name
  title
  isNew
}

After the request completes, each field will be available as a property on data under the provided alias. In the example above, we aliased both fields, but you could omit the alias from one of them.