【问题标题】:Angular 2 - Typescript: TS2322: Type 'Subscription' is not assignable to type 'Observable<MouseEvent>'Angular 2 - Typescript:TS2322:类型“订阅”不可分配给类型“Observable<MouseEvent>”
【发布时间】:2017-05-06 23:26:19
【问题描述】:

我正在使用这个 plunk 中的 click-outside 指令 --> http://embed.plnkr.co/v7BMUv/

我的 TS 编译器抛出以下错误:

TS2322:“订阅”类型不可分配给“可观察”类型。 “订阅”类型中缺少属性“_isScalar”。

TS2339 属性“取消订阅”在“可观察”类型上不存在。

我的 tsconfig.json:

{
  "compileOnSave": false,
  "compilerOptions": {
    "target": "es6",
    "module": "system",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "removeComments": false,
    "suppressImplicitAnyIndexErrors": true,
    "noImplicitAny": false,
    "noEmitOnError": false
  },
  "exclude": [
    "node_modules",
    "wwwroot"
  ]
}

导致错误的代码:

  ngOnInit() {
    this.globalClick = Observable
      .fromEvent(document, 'click')
      .delay(1)
      .do(() => {
        this.listening = true;
      }).subscribe((event:MouseEvent) => {
        this.onGlobalClick(event);
      });
  }
  

我该如何克服这个错误?

【问题讨论】:

  • 此错误与 TypeScript 静态代码分析有关。粘贴导致此错误的代码。
  • 编辑添加代码

标签: angular typescript mouseevent rxjs observable


【解决方案1】:

错误在click-outside.directive.tsObservable.subscribe 返回一个 Subscription(在 ngOnInit 中),而不是另一个 Observable。因此,private globalClick 的类型应该是Subscription

当类型被删除时它可以工作,并且由于 plunker 不显示类型错误它可以工作,但是当使用 tsc 编译时它会出错,因为你试图将 Subscription 对象分配给 Observable .

【讨论】:

    猜你喜欢
    • 2019-08-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-12
    • 2021-05-21
    • 1970-01-01
    • 2020-04-26
    • 1970-01-01
    • 2020-11-23
    相关资源
    最近更新 更多