【问题标题】:TSLint annoying messageTSLint 烦人的消息
【发布时间】:2018-06-20 18:58:38
【问题描述】:

在我的 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);
        });
  }
}

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

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

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

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

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

【问题讨论】:

标签: javascript angular typescript rxjs tslint


【解决方案1】:

正如一些 cmets 中所解释的,这不是 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 工作正常)。

【讨论】:

  • 我尝试了您的替代方案,但即使编译成功并且应用程序运行正常,vscode 仍然给我警告[ts] Property 'debounceTime' does not exist on type 'Observable<any>'.。这有点烦人。
  • import { debounceTime, distinctUntilChanged } from 'rxjs/operators'; //它是否错过了“来自”?
猜你喜欢
  • 1970-01-01
  • 2017-07-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-19
  • 2017-10-09
  • 2014-06-10
  • 1970-01-01
相关资源
最近更新 更多