每个函数调用清除超时Angular2 RxJS

每个函数调用清除超时Angular2 RxJS

问题描述:

我有一个http请求,如果用户在输入内输入至少4个字符,并且每次更改其内容(添加/删除字母)时触发该请求。我想添加一个超时,如果用户开始输入字符,函数将等待1秒钟,直到它触发请求,以避免用户在快速输入时出现很多请求。我尝试:每个函数调用清除超时Angular2 RxJS

if (this.pointName.length >= 3) { 
    let timer = function() { 
    this.http.get(`./points.json`) 
     .subscribe(res => { 
      this.pointsArray = res.json(); 
     }); 
    }; 
clearTimeout(timer); 
setTimeout(timer,1000); 

我的想法是,以清除每个keyup事件超时,并再次进行设置。 但不幸的是,它给了我一个错误,'类型'()=> void'的参数不能分配给'number'类型的参数。

有没有办法更有效地做到这一点?也许使用RxJS?无论如何,我正在寻找一个可行的解决方案。先谢谢你。

HTML

<input type="text" id="searchInput" placeholder="Point name"(keyup)="getPoints()"> 
+0

为更好的方法你的场景是使用rxjs'debounce'运算符。 –

为什么不使用debounceTime(500),而不是setTimeout的。

所有的

https://www.learnrxjs.io/operators/filtering/debouncetime.html

+0

如果你有一个账户在egghead这个视频是非常有用的你的情况。 https://egghead.io/courses/build-an-angular-2-instant-search-component – silvelo

+0

它在我的情况下会是什么样子?我已经发布了keyup事件的HTML代码。 – dragon

+0

Punker简单示例:https://plnkr.co/6xFvxfhmUROt68hCpgIh – silvelo

首先,你最好使用Debounce运营商RxJS。 而你的代码中的问题是,你应该通过timer_idclearTimeout而不是该函数。

if (this.pointName.length >= 3) { 
    let timer = function() { 
    this.http.get(`./points.json`) 
     .subscribe(res => { 
      this.pointsArray = res.json(); 
     }); 
    }; 
let timer_id = undefined; 
clearTimeout(timer_id); 
timer_id = setTimeout(timer,1000); 

试试这个:

创建RxJS主题为您的组件的新成员变量

searchTerm$ = new Subject<string>(); 

在组件的ngOnInit方法,建立你的观察到的,

ngOnInit() { 
    this.searchTerm$ 
     .filter(value => value.length >= 3) 
     .debounceTime(1000) 
     .switchMap(val => { 
     return this.http.get('./points.json') 
         .map(result => result.json()); 
     }) 
     .subscribe(result => .... // do what you want with the response); 
} 

在您的HTML中,更改您的键盘事件绑定以提交输入字段的值

<input type="text" id="searchInput" placeholder="Point name"(keyup)="getPoints(this.value)"> 

然后在组件的getPoints方法,发送一个值,你的主题$

getPoints(value) { 
    this.subject$.next(value); 
} 

基本上,你创建的可观察做几件事情:

searchTerm$ 
    .filter(value => value.length >= 3) // 1 filter out search terms that are shorter than 3 characters 
    .debounceTime(1000)     // 2. only send events after no event comes for 1 sec 
    .switchMap(val => {     // 3. convert your value to the result of your http request 
    return this.http.get('./points.json') 
        .map(result => result.json()); 
    }) 
    .subscribe(result => .... // do what you want with the response);