TSLint 烦人的消息

xco*_*ode 2 javascript rxjs typescript tslint angular

在我的 angular 组件上,我使用了来自 RxJs 的两种方法,debounceTime()以及distinctUntilChanged()

import { Component, OnInit } from '@angular/core';
import { FormControl } from '@angular/forms';

import 'rxjs/add/operator/debounceTime';
import 'rxjs/add/operator/distinctUntilChanged';

@Component({
  selector: 'app-form4th',
  templateUrl: './form4th.component.html',
})
export class Form4thComponent implements OnInit {
  searchField: FormControl;
  searches: string[] = [];

  constructor() { }

  ngOnInit() {
    this.searchField = new FormControl();
    this.searchField
        .valueChanges
        .debounceTime(400)
        .distinctUntilChanged()
        .subscribe(term => {
          this.searches.push(term);
        });
  }
}
Run Code Online (Sandbox Code Playgroud)

应用程序工作正常,在执行(构建)ie 时没有错误甚至没有警告消息ng serve,并且在浏览器上运行应用程序按预期工作,并且在浏览器控制台上也没有错误消息或警告。

但是,我的 vscode 上有一条奇怪的 TSLint 消息说:

[ts] Property 'debounceTime' does not exist on type 'Observable<any>'.

这有点烦人,因为我有点担心某些事情在我不知道的引擎盖下不起作用。

我在这里缺少什么?谢谢你。

max*_*992 5

正如一些评论中所解释的,这不是 TSLINT 错误,而是 Typescript 错误。

这里的事情,你正在修补Observable你这样做时的原型: import 'rxjs/add/operator/debounceTime'; import 'rxjs/add/operator/distinctUntilChanged';

而不是这样做,您可能只想利用lettable operators自 rxjs v5.5 以来称为的新功能。它让你使用一个新的.pipe运算符,它将函数作为参数(rxjs 运算符或你自己的)。

因此,请尝试以下代码而不是您的代码:

import { Component, OnInit } from '@angular/core';
import { FormControl } from '@angular/forms';

// notice this import will not patch `Observable` prototype
import { debounceTime, distinctUntilChanged } from 'rxjs/operators';

@Component({
  selector: 'app-form4th',
  templateUrl: './form4th.component.html',
})
export class Form4thComponent implements OnInit {
  searchField: FormControl;
  searches: string[] = [];

  constructor() { }

  ngOnInit() {
    this.searchField = new FormControl();

    this.searchField
      .valueChanges
      .pipe(
        debounceTime(400),
        distinctUntilChanged()
      )
      .subscribe(term => {
        this.searches.push(term);
      });
  }
}
Run Code Online (Sandbox Code Playgroud)

通过不修补Observable它的原型将帮助您的捆绑器进行摇树(如果可用),但我相信 Typescript 进行必要的检查会更容易,因为这些函数必须导入到同一文件中。(也就是说,我一直在使用旧的时尚方法,VSC 按预期工作)。