Angular 2 - Typescript:TS2322:类型“订阅”不可分配给类型“Observable<MouseEvent>”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41264465/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 04:06:21  来源:igfitidea点击:

Angular 2 - Typescript: TS2322: Type 'Subscription' is not assignable to type 'Observable<MouseEvent>'

angulartypescriptmouseeventrxjsobservable

提问by Shilpa Nagavara

I am using the click-outside directive from this plunk --> http://embed.plnkr.co/v7BMUv/

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

My TS compiler is throwing the following errors:

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

TS2322: Type 'Subscription' is not assignable to type 'Observable'. Property '_isScalar' is missing in type 'Subscription'.

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

TS2339 Property 'unsubscribe' does not exist on type 'Observable'.

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

My tsconfig.json:

我的 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"
  ]
}

The code causing error:

导致错误的代码:

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

How do I overcome this error?

我如何克服这个错误?

回答by Ionut Costica

The error is in click-outside.directive.ts. Observable.subscribereturns a Subscription(in ngOnInit), not another Observable. Thus, the type of private globalClickshould be Subscription.

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

It works when types are removed, and as plunker doesn't show type errors it worked, but when compiling with tscit will error out as you're trying to assign a Subscriptionobject to an Observable.

它在删除类型时起作用,并且由于 plunker 不显示它起作用的类型错误,但是当tsc您尝试将Subscription对象分配给Observable.