angular - 如何从订阅返回数据到 HttpClient
问题描述
我正在实现搜索并尝试使用异步管道和 http 客户端。我应该如何将服务中的 observable 作为定义数组返回?该服务使用 HttpClient 获取一些数据,我需要将其映射到定义列表。安静与rxjs混淆,我应该管道和映射,还是在订阅函数中返回数据或返回observable?
export class DefinitionService {
constructor(private http: HttpClient) { }
searchTerm(term: string) {
return this.http.get('http://localhost:8080/api/search?term=abc')
.subscribe((data: string) => {
// Data extraction from the HTTP response is already done
// Display the result
console.log('TJ user data', data);
});
}
}
在组件中使用 rxjs 运算符处理搜索的代码:
searchInput = new FormControl();
constructor(private definitionService: DefinitionService) {
this.definitions = this.searchInput.valueChanges
.pipe(
startWith(''),
debounceTime(500),
distinctUntilChanged(),
switchMap(value => this.definitionService.searchTerm(value))
)
}
模板:
<input class="format-input-button"
(click)="clickInput()"
[formControl]="searchInput">
<div class="format-options">
<div *ngFor="let definition of definitions" class="search-result" (click)="selectResult('test result')">
<div>{{definition.name}}</div>
<div>{{definition.description}}</div>
</div>
</div>
我可以做这样的事情吗?
searchTerm(term: string) {
return this.http.get('http://localhost:8080/api/search?term=abc')
.pipe(
map(result => {
// do mapping here
return mappedData;
})
);
}
有人建议使用异步管道,我应该在搜索结果 Observable 上使用它吗?如果我使用异步管道,我还需要 switchMap 吗?
解决方案
推荐阅读
- python-3.x - Python 3:从 numpy 数组中选择随机对元素而不重复
- ios - 带有 Alamofire 和 ObjectMapper 的 Swift 4.0 没有这样的模块“ObjectMapper”
- javascript - 如何在我的网站上隐藏代码/文件?
- python - 在 python 下拟合时选择步长
- optimization - 使用 scipy.optimize curve_fit 在 Python 中进行曲线拟合
- javascript - 使用javascript处理诺基亚按钮连续点击
- ajax - 动态添加/删除输入字段以形成(Symfony 3 事件/Ajax)
- vb.net - 从文本文件添加到列表视图的第一项只是添加了两次
- tensorflow - Tensorflow-没有名为“object_detection.protos”的模块
- vb.net - 在比较时添加仅存在于 file1 中的数据