要在搜索栏输入时停止可观察计时器,我们需要使用rxjs的操作符。我们可以使用Subject来发出输入事件,并使用switchMap操作符来停止并重新启动计时器。
下面是一个示例代码:
import { Component, OnDestroy } from '@angular/core';
import { Subject, Observable, timer } from 'rxjs';
import { switchMap, takeUntil } from 'rxjs/operators';
@Component({
selector: 'app-search',
template: `
`
})
export class SearchComponent implements OnDestroy {
search = new Subject();
private ngUnsubscribe = new Subject();
constructor() {
const timer$ = timer(0, 2000);
this.search.pipe(
switchMap((term) => {
return timer$.pipe(
takeUntil(this.search),
takeUntil(this.ngUnsubscribe)
);
})
).subscribe(() => {
console.log('timer fired');
});
}
ngOnDestroy() {
this.ngUnsubscribe.next();
this.ngUnsubscribe.complete();
}
}
在上面的代码中,我们创建了一个名为search的Subject对象,它将输入事件发送到观察者流中。我们使用switchMap操作符来订阅搜索事件,每次搜索事件都会停止并重新启动计时器。使用takeUntil运算符,我们还可以在组件被销毁时正确清理我们的可观测对象,避免内存泄漏。当我们运行此代码时,我们应该能够在控制台中看到'timer fired”消息。