Apollo Client Angular:如何将从一个查询中获得的数据作为参数传递到graphql中的另一个查询



我使用apollo-clinet angular从使用graphql的第三方获取数据。我想使用从graphql查询中获得的一些数据来用于另一个graphql查询。例如


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

我想在另一个查询中使用this.customerId作为参数,如下所示:

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

但我没有从第二个查询中获得数据,因为代码块没有执行,因为this.customerId是未定义的(当我调试代码时发现(。有人能帮我吗?。

变量this.customerId是异步初始化的。第二个调用必须与第一个调用耦合。这取决于你希望如何执行它们。一种最快的方法是使用像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); }
);

最新更新