angular - 需要帮助将加载指示器添加到订阅 Rxjs 主题的搜索栏
问题描述
我有一个搜索栏字段,我使用服务来运行我的搜索功能,如下所示:
// signup.ts
ngOnInit() {
this.filteredOptions$ = this.searchService.search(this.searchTerm$);
}
搜索词是主题的地方:
<input type="text" placeholder="Your Business Name" aria-label="Number" matInput (keyup)="searchTerm$.next($event.target.value)"
[matAutocomplete]="auto">
我想在搜索功能启动和完成时显示加载指示器,但问题是这是一项服务(使用可注入)。这是我的搜索功能:
// searchservice.ts
public search(terms: Observable<string>): Observable<ABN> {
return terms.pipe(
debounceTime(400),
distinctUntilChanged(),
switchMap(term => this.searchEntries(term)),
);
}
然后我在我的模板上订阅这个。如何将其作为服务保存在单独的文件中,但仍更新组件上的局部变量(isLoading)?
解决方案
只需向您的组件添加一个加载变量,然后在您的组件中管道您的源和目标可观察对象:
ngOnInit() {
this.filteredOptions$ = this.searchService.search(
this.searchTerm$.pipe(tap(() => this.loading = true)
).pipe(finalize(() => this.loading = false));
}
这让组件中的加载标志保持关注,我同意它所属的位置。
推荐阅读
- reactjs - 如何在 Heroku 上使用 React 和 Flask 创建部署管道?
- javascript - 使用自身构造函数初始化对象属性
- robotframework - 使用前面声明的变量创建列表
- javascript - 如何使用 axios 并获取 JSON 数据
- html - 为什么 robots.txt 很重要?没有 robots.txt 的网站是否安全?
- facebook-graph-api - Leadgen Webhook:请求此资源需要用户访问令牌
- javascript - XSS 攻击和编码
- javascript - 导航器/窗口更改时如何更新反应钩子?
- keycloak - 无法从 keycloak 建立到 Mailhog 的 SMTP 连接
- java - java.lang.Error:java.lang.reflect.InvocationTargetException