Search code examples
angulargraphqlapollo

Apollo Client Angular: how to pass the data obtained from a query as an argument in another query in graphql?


I am using apollo clinet angular to fetch data from a third party who uses graphql. I would like to use some data that is obtained from a graphql query to be used in another graphql query. For example


const customer = gql`query customer{
    customer {
      id
    }
....
....

this.apollo.watchQuery({
   query: customer
}).valueChanges.subscribe((customer: any) => {
 this.customerId = customer.data?.customer.id;
});

I want to use this.customerId as an argument in another query like as follows:

const customerInformation = gql` 
query customerInformation($customer: Long!){
customerInformation{
  first_name
  last_name
  address
}
}`;
....
....
if(this.customerId){
this.apollo.watchQuery({
 query: customerInformation,
 variables: {
  customer: this.customerId
},
})
 .valueChanges.subscribe((result: any) => {
  console.log(result);
 });
}

But i am not getting the data from the second query as the block of code is not executed because the this.customerId is undefined (found that when i debugged through the code). Can someone help me here ?.


Solution

  • The variable this.customerId is initialized asynchronously. The second call must be coupled with the first call. That depends on how you wish for them to be executed. One quickest way is to map from one observable to another using a higher order mapping operator like switchMap.

    import { NEVER } from 'rxjs';
    import { switchMap } from 'rxjs/operators';
    
    const customer = gql`query ...`;
    
    this.apollo.watchQuery({ query: customer }).valueChanges.pipe(
      switchMap((customer: any) => {   // <-- map to other observable
        this.customerId = customer;
        const customerInformation = gql` query ...`;
        if (!!customer) {
          return this.apollo.watchQuery({
            query: customerInformation,
            variables: {
              customer: this.customerId
            },
          }).valueChanges;
        }
        return NEVER;  // <-- do NOT emit if `customer` is undefined
    ).subscribe(
      (value: any) => { console.log(result); },
      (error: any) => { console.log(error); }
    );