TSLint烦人的消息

时间:2018-01-11 12:33:41

标签: javascript angular typescript rxjs tslint

在我的角色组件上,我使用了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);
        });
  }
}
在执行(构建)即ng serve时,

应用程序正常无错误甚至没有警告消息,并且在浏览器上运行应用程序正如预期的那样,并且在浏览器控制台上也没有错误消息或警告。

然而,我的vscode上有这个奇怪的TSLint消息说:

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

这有点烦人,因为我有点担心在我不知道的情况下工作不起作用。

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

1 个答案:

答案 0 :(得分:4)

正如一些评论中所解释的那样,它不是TSLINT错误,它是一个Typescript错误。

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

您可能只想利用自rxjs v5.5以来名为lettable operators的新功能,而不是这样做。它允许你使用一个新的.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);
      });
  }
}

通过不修补Observable的原型,它会帮助您的捆绑器进行树摇动(如果可用)但我确信它可以更容易地使用Typescript来完成必要的操作检查,因为必须在同一文件中导入函数。 (也就是说,我已经使用旧时尚方法一段时间了,VSC按预期工作)。

相关问题