我在试图创建将keyup事件转换为可观察的流时遇到了问题。
我是跟随吴书版本6。我被困在一个例子,使搜索YouTube视频,因为你键入。当搜索返回时,我们将显示一个视频缩略图结果列表,以及一个描述和每个视频的链接。
为此,我们使用了一个observable.fromEvent:https://github.com/NiLinli/ng-book2-angular-6-r68-code-samples/blob/master/http/src/app/you-tube-search/search-box.component.ts
在RxJS 5中,它提供了一种使用Rx.Observable.fromEvent侦听元素上的事件的方法。
ngOnInit(): void {
// convert the `keyup` event into an observable stream
Observable.fromEvent(this.el.nativeElement, 'keyup')但是我发现了一个错误:
src/app/search-box/search-box.component.ts(42,13):ERROR TS2339中的错误:在“可观察类型”类型中不存在属性'fromEvent‘。
我RxJS 6可观察到的导入和fromEvent如下所示:
import { Observable, fromEvent } from 'rxjs';这是我在角6中的RxJs5版本的代码:(它不工作)
Observable.fromEvent(this.el.nativeElement, 'keyup')
.map((e: any) => e.target.value) // extract the value of the input
.filter((text: string) => text.length > 1) // filter out if empty
.debounceTime(250) // only once every 250ms
.do(() => this.loading.emit(true)) // enable loading
// search, discarding old events if new input comes in
.map((query: string) => this.youtube.search(query))
.switch(),这是我用RxJs 6和角6做的尝试(它是根据最后的答案更新的)
我试图使用管道语法:
const obs = fromEvent(this.el.nativeElement, 'keyup')
.pipe (
.map((e:any) => e.target.value) // extract the value of the input
// .filter((text:string) => text.length > 1) //filter out if empty
.debounceTime(250) //only search after 250 ms
.tap(() => this.loading.emit(true)) // Enable loading
// search, call the search service
.map((query:string) => this.youtube.search(query))
// discard old events if new input comes in
.switchAll()
// act on the return of the search
) 但我有个错误:
可观察到的{<>}类型上不存在属性“map”
在命令行中,运行ng服务后:
搜索框/搜索框中的错误。组件. in (40,4):错误TS1135:参数>预期表达式。搜索框/搜索框.组件. or (54,4):错误TS1128:预期的声明或>语句。
但是,这不管用.那么,我该怎么写我的烟斗税呢?
我的研究进展如何:
发布于 2018-06-16 21:29:56
在您的情况下,这应该是可行的:
import { fromEvent } from 'rxjs';
import { map, filter, debounceTime, tap, switchAll } from 'rxjs/operators';
const obs = fromEvent(this.el.nativeElement, 'keyup')
.pipe (
map((e:any) => e.target.value), // extract the value of the input
// filter((text:string) => text.length > 1), //filter out if empty
debounceTime(250), //only search after 250 ms
tap(() => this.loading.emit(true)), // Enable loading
// search, call the search service
map((query:string) => this.youtube.search(query)) ,
// discard old events if new input comes in
switchAll()
// act on the return of the search
) 希望能帮上忙!
这里是Stackblitz:上的一个工作演示:演示角6+ Rxjs 6
发布于 2018-05-29 05:57:09
在RxJS 5中,你在写
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/of';
import 'rxjs/add/operator/map';RxJS 6的进口发生了变化
import { Observable, of, Subject, Subscription } from 'rxjs';
import { map, filter, debounceTime, distinctUntilChanged } from 'rxjs/operators';有关更多信息,请查看RxJS迁移指南。
https://stackoverflow.com/questions/50571550
复制相似问题