Angular 如何将输入变量传递给服务变量

Angular 如何将输入变量传递给服务变量,angular,Angular,我正在从事一个Angular web项目,发现很难通过向服务传递用户输入字段来获取API端点上的请求 因此,将page.component.ts中的inputKeyword重新分配给service.ts中的输入 input; getData() { return this.http.get('url?key=' + environment.apiKey + '&cx=' + environment.cx + '&q=' + this.input) }

我正在从事一个Angular web项目,发现很难通过向服务传递用户输入字段来获取API端点上的请求

因此,将page.component.ts中的inputKeyword重新分配给service.ts中的输入

input;

getData() {
    return   this.http.get('url?key='
     + environment.apiKey + '&cx=' + environment.cx + '&q=' + this.input)
  }
我需要用正确的方法来做

page.component.html

<input id="search" type="text"  [(ngModel)]="inputKeyword" name="search" />


 <button  (click)="searchData()"> Search </button>
data.service.ts

input;

getData() {
    return   this.http.get('url?key='
     + environment.apiKey + '&cx=' + environment.cx + '&q=' + this.input)
  }

您正在从未定义输入属性的服务订阅该方法。您仅在订阅中分配了一个值,在这种情况下,该值是错误的

服务中的方法应如下所示:

getData(input: string) {
   return   this.http.get('url?key='
    + environment.apiKey + '&cx=' + environment.cx + '&q=' + input)
 }
在组件中,将inputKeyword属性作为参数传递给该方法,如下所示:

searchData(){ 
      return this.googleService.getData(this.inputKeyword).subscribe(x =>{
        this.googleData= x.items;
        console.log(this.googleData)
       }, error => {
         console.log(error)
       })

在哪里调用getData方法?我在你的代码里没看到。此处显示的代码不完整,因此我们无法帮助您。考虑创建一个StasBLITZ项目。@ IONUT-T请更新代码