Observable.fromEvent - RXJS

时间:2018-05-15 16:56:53

标签: angular rxjs angular6

我试图从输入事件创建一个Observable。我已经尝试过几乎所有的东西而且我无法导入" fromEvent"。这是我的代码。我使用角度6.0.1和RXJS 6.1.0

错误TS2339:Property' fromEvent'在类型' typeof Observable'。

上不存在
import { Directive, EventEmitter, Input, Output, ElementRef, ViewChild, AfterViewInit } from '@angular/core';
import { NgControl } from '@angular/forms';
import { distinctUntilChanged } from 'rxjs/internal/operators/distinctUntilChanged';
import { debounceTime } from 'rxjs/internal/operators/debounceTime';
import { map } from 'rxjs/internal/operators/map';
import { filter } from 'rxjs/internal/operators/filter';
import { Observable } from 'rxjs/internal/Observable';
//import 'rxjs/internal/observable/fromEvent';
//import 'rxjs/add/observable/fromEvent';

@Directive({
  selector: '[ngModel][debounceTime]'
})
export class InputDebounceDirective implements AfterViewInit {

  @Output()
  public onDebounce = new EventEmitter<any>();

  @Input('debounceTime')
  public debounceTime: number = 1500;

  constructor(private elementRef: ElementRef, private currentModel: NgControl) { }

  ngAfterViewInit() {
    Observable.fromEvent(this.elementRef.nativeElement, 'keyup')
      .pipe(
        debounceTime(this.debounceTime),
        distinctUntilChanged()
      )
      .subscribe(x => {
        this.onDebounce.emit(x);
      });

  }

}

1 个答案:

答案 0 :(得分:15)

您必须在RxJS6中导入fromEvent,如下所示:

import {fromEvent} from 'rxjs';

请阅读migration guide以获取更多信息,特别是请查看import paths部分。

使用fromEvent时,请将其用作以下函数:

fromEvent(this.elementRef.nativeElement, 'keyup')

不是如下的静态方法(这在以前的RxJS版本中是正确的)

Observable.fromEvent(this.elementRef.nativeElement, 'keyup')