如何将参数从UI传递到graphql以获取数据

时间:2019-04-09 10:49:18

标签: angular typescript graphql apollo

我有一个graphQl网址,可以从后端获取数据。 但是,问题是当前我正在提供客户的硬编码ID以获取数据。 我想创建一个输入框,然后允许用户通过输入客户ID来获取任何客户记录。 当前要获取客户记录的硬编码代码:

ngOnInit() {
this.apollo
.watchQuery({
  query: gql`
    {
      findCustomer(id: "UF2aLa1L687") {
        id
        customerType
      }
    }
  `,
})
.valueChanges.subscribe(result => {
  this.customer = result.data ;
  this.loading = result.loading;
  this.error = result.errors;
  console.log('Customer Info', this.customer);
  console.log('Loading', this.loading);
  console.log('Error', this.error);

});

}

如何从UI传递值,我需要一些类似于使用ngModel进行角度双向绑定的操作。 我尝试了这段代码,但是出现了Unterminated String错误。

  searchByCustomerIdGraphQL() {
console.log(this.customerIdValue);
this.isLoadingResults = true;
this.apollo.watchQuery({
  query: gql`
  {
    findCustomer(id : "` + this.customerIdValue + `") {
      id
    }
  }
  }`
}).valueChanges.subscribe( result => {
  this.customerSearchRecord = result.data;
  this.loading = result.loading;
  this.error = result.errors;
});
}

有人可以帮我弄清楚如何传递值吗?

1 个答案:

答案 0 :(得分:0)

分别定义您的查询,以下原因更容易理解:

import ast
x = "b\'<article> \\n L\\xc3\\xa4s bl.a. om Gasporox nya m\\xc3\\xa4tkoncept f\\xc3\\xb6r tr\\xc3\\xa5g, en intervju med styrelseledamoten Per Nystr\\xc3\\xb6m och nyheter fr\\xc3\\xa5n GPX Medical om bland annat projekten Sinuslight och Neo-Lung.\\n</article>'"

x = ast.literal_eval(x)

result = x.decode("utf-8")

如上所述,您可以在查询本身中使用变量。

然后,您可以将变量传递给const findCustomerQuery = gql` query FindCustomer($id: String!) { findCustomer(id: $id) { id customerType } } `; 的{​​{1}}选项:

watchQuery

docs

中的更多信息