我正在尝试将下面的示例link应用于我的有角度的前端应用程序。
它应该使用输入字段中的搜索参数向我的后端发出一个get请求。键入后,它总是将GET调用触发到我的后端,但是参数始终是一个空字符串。
在我的代码下面:
app.component.ts:
export class AppComponent implements AfterViewInit {
searchBox = null;
autoComplete = null;
constructor(private apiService: ApiService) { }
ngAfterViewInit(): void {
this.searchBox = document.getElementById('searchBox');
this.autoComplete = fromEvent(this.searchBox, 'input').pipe(
map((e: KeyboardEvent) => (<HTMLTextAreaElement>e.target).value),
filter(text => text.length > 2),
debounceTime(250),
distinctUntilChanged(),
switchMap(s => this.apiService.autoComplete(s))
);
}
}
app.component.html:
<div>
<input type="text" id="searchBox">
<pre>
{{autoComplete | async | json}}
</pre>
</div>
api.service.ts:
export class ApiService {
autoComplete(s: string): Observable<KeyNames[]> {
const params = new HttpParams();
params.append('search', s);
return this.httpClient.get<KeyNames[]>(this.API_URL + '/tags/autoComplete', {params})
.pipe(
catchError(this.handleError('autoComplete', []))
);
}
}
谁能告诉我为什么我的autoComplete()函数总是以空字符串调用?
答案 0 :(得分:2)
这里的问题可能与append
方法有关,因为它返回了HttpParams
,这可能意味着您应该这样做:
let params = new HttpParams();
params = params.append('search', s);
或简单地:
const params = new HttpParams().set('search', s);