rxjs 交换机映射类型不匹配问题



我正在尝试在我的应用程序中使用 ng-bootstrap 实现一个预类型。 我正在遵循维基百科示例,它使用维基百科服务获取数据。

我已经在我的应用程序中实现了类似的东西,但我在rxjsswitchMap函数中遇到了类型不匹配问题。

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)
)

我的问题是,当我尝试实现这一点时,switchMap内的term是一个Observable<{}>而不是一个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

堆栈闪电战演示。 如果您查看appapp.component.ts,则会出现 TS 检查错误。

在我的评论之后,你有一个括号问题。在这里,工作。

/*
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)
)
};

相关内容

  • 没有找到相关文章

最新更新