[英]How to pass input variable to a service Angular
I'm working on an Angular web project and finding it difficult to pass a user input field to service to get a request on an API endpoint.我正在处理一个 Angular Web 项目,发现很难将用户输入字段传递给服务以获取 API 端点上的请求。
so reassigning the inputKeyword in the page.component.ts to the input in the service.ts因此将 page.component.ts 中的 inputKeyword 重新分配给 service.ts 中的输入
I will need to do it the right way我需要以正确的方式去做
page.component.html页面.component.html
<input id="search" type="text" [(ngModel)]="inputKeyword" name="search" />
<button (click)="searchData()"> Search </button>
page.component.ts page.component.ts
inputKeyword : string = '';
searchData(){
return this.googleService.getData().subscribe(x =>{
this.googleData= x.items;
console.log("input ",this.inputKeyword)
this.inputKeyword = this.googleService.input;
console.log(this.googleData)
}, error => {
console.log(error)
})
}
data.service.ts数据服务.ts
input;
getData() {
return this.http.get('url?key='
+ environment.apiKey + '&cx=' + environment.cx + '&q=' + this.input)
}
You are subscribing to the method from the service where the input
property is undefined.您正在从未定义
input
属性的服务订阅该方法。 You assign a value only in the subscription which is wrong in this case.您只在订阅中分配一个值,在这种情况下是错误的。
Your method from the service should be like this:你的服务方法应该是这样的:
getData(input: string) {
return this.http.get('url?key='
+ environment.apiKey + '&cx=' + environment.cx + '&q=' + input)
}
And in the component you pass the inputKeyword
property as an argument to that method like so:在组件中,您将
inputKeyword
属性作为参数传递给该方法,如下所示:
searchData(){
return this.googleService.getData(this.inputKeyword).subscribe(x =>{
this.googleData= x.items;
console.log(this.googleData)
}, error => {
console.log(error)
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.