如何向GraphQL查询传递参数? [英] How to pass parameter to graphql query?
本文介绍了如何向GraphQL查询传递参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试在一个流星烈焰项目中使用Apollo GraphQL。
我正在使用swydo:blaze-apollo
中的包。
可以使用GraphQL查询从MongoDB获取数据。
// Using this one can get data
const LOCATION_COUNTRY_QUERY = gql`
{
locations(location_type: "Country"){
location_id
name
iso_code
}
}
`;
Template.home.onCreated(function(){
const country = this.gqlQuery({query: LOCATION_COUNTRY_QUERY}).get();
console.log(country.locations); // Which will show an array list of country.
});
但是,我不想在查询中硬编码"Country"。我想将字符串传递给查询,然后使用其他LOCATION_TYPE获取数据。但我找不到任何关于它的文章,gql语法只是阻止任何参数。
任何人都有类似的经历,可以给出任何建议吗?
推荐答案
您可以使用GraphQL变量来完成该工作。
首先,将变量声明为LOCATION_COUNTRY_QUERY
:
const LOCATION_COUNTRY_QUERY = gql`
query locationCountryQuery($locationType: String!){
locations(location_type: $locationType){
location_id
name
iso_code
}
}
`;
现在您可以为查询提供新的variables
选项:
Template.home.onCreated(function(){
const country = this.gqlQuery({query: LOCATION_COUNTRY_QUERY, variables: {locationType: "Country"}).get();
console.log(country.locations); // Which will show an array list of country.
});
这篇关于如何向GraphQL查询传递参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文