angular - rxjs switchMap 类型不匹配问题
问题描述
我正在尝试在我的应用程序中使用 ng-bootstrap 实现预输入。我正在关注使用 WikipediaService获取数据的wikipedia 示例。
我在我的应用程序中实现了类似的东西,但是我在switchMap
函数中遇到了类型不匹配的问题rxjs
。
来自 ng-bootstrap 的示例:
search = (text$: Observable<string>) =>
text$.pipe(
debounceTime(300),
distinctUntilChanged(),
tap(() => this.searching = true),
switchMap(term =>
this._service.search(term).pipe(
tap(() => this.searchFailed = false),
catchError(() => {
this.searchFailed = true;
return of([]);
}))
),
tap(() => this.searching = false)
)
我的问题是,当我尝试实现此功能时,term
insideswitchMap
是 anObservable<{}>
而不是 a string
,因此我无法将其传递给我的服务。
如何从可观察对象中获取实际值以传递给我的服务?
我的版本:
search = (text$: Observable<string>) =>
text$.pipe(
debounceTime(300),
distinctUntilChanged(),
tap(() => this.searching = true),
switchMap(term =>
this.placeService.search(term).pipe( // [ts] Argument of type 'Observable<{}>' is not assignable to parameter of type 'string'.
tap(() => this.searchFailed = false),
catchError(() => {
this.searchFailed = true;
return of([]);
})
),
tap(() => this.searching = false))
)
更新 1
StackBlitz 演示。如果你看app\app.component.ts
,你会得到 TS linting 错误。
解决方案
根据我的评论,您遇到了括号问题。在这里,工作。
/*
Observables are streams that can be monitored. It means that when you
subscribe to it, everytime a value is emitted, your subscribe function
will be triggered (or in this case, the pipe functions, because you
subscribe to search() in another component)
*/
search(text$: Observable<string>) {
return text$
// pipe = perform operations on the value before sending it to subscribe
.pipe(
// debounceTime = wait 300ms before emitting. If a new value is emitted,
// cancel the previous one
debounceTime(300),
// distinctUntilChanged = if the value is the same as the previous one, cancel
distinctUntilChanged(),
// tap = perform an operation without touching the value emitted
tap(() => this.searching = true),
// switchMap = cancel previous HTTP requests if they're not finished
switchMap(term => this.placeService.search(term).pipe(
tap(() => this.searchFailed = false),
// catchError = self-explanatory :)
catchError(() => {
this.searchFailed = true;
return of([]);
})
)),
tap(() => this.searching = false)
)
};
推荐阅读
- django - 表单数据未保存在 Django 的数据库中
- javascript - 重启 EC2 实例后 AWS S3 存储桶未重新挂载
- swift - 这个简单的 Swift 函数构建器示例有什么问题?
- angularjs - Django Angular 社交媒体身份验证
- angular - 使用 `element.all(by.id())` 获取元素数量
- c# - 如何在使用 EF 6 的数据库设计中容纳父表的默认值?
- java - 加倍到 int 和加倍到 int
- wpf - 在 WPF 数据网格 MVVM 中创建倒数计时器列
- scrapy - Scrapy过滤器相同的url在“http”和“https”中不同
- swift - “minimumFetchInterval”未在“RemoteConfigSettings”中定义