【问题标题】:Context 'this' of EventEmitter <string> is not assigned to the 'this' method of type Observable <string>EventEmitter <string> 的上下文 'this' 未分配给 Observable <string> 类型的 'this' 方法
【发布时间】:2018-11-04 02:56:55
【问题描述】:

我查看了 GitHub 存储库中的示例。一个应用程序成功执行并且编写的代码通常可以工作,但是我的 Visual Studio 代码中有以下错误:

“EventEmitter”类型的“this”上下文不可分配给“Observable”类型的方法“this”。\n 属性“lift”的类型不兼容。\n 类型“(operator: Operator) => Observable ' 不可分配给类型 '(operator: Operator) => Observable'。\n 类型 'Observable' 不可分配给类型 'Observable'。\n 类型 'string' 不可分配给类型 'R'。

产生错误的代码如下:

this.notificationService.notifier
.do(message => {
  this.message = message;
  this.snackVisibility = 'visible'; 
})
.switchMap(message => Observable.timer(2000))
.subscribe(timer => this.snackVisibility = 'hidden');

我所有的服务文件代码如下:

import { EventEmitter } from "@angular/core";

export class NotificationService {
   notifier = new EventEmitter<string>();

   notify(message: string) {
      this.notifier.emit(message);
   }
}

虽然应用程序运行良好,但 VS Code 给了我错误,如图所示:

这个错误的最佳解决方案是什么?

【问题讨论】:

  • 你的 RxJs 版本是多少?
  • @Vikas 我的 package.json 中 RxJs 的版本是 5.1.0
  • 请同时包含“this.notificationService.notifier”代码,有助于调试问题
  • 好吧,@SureshKumarAriya。这是包含 NotificationService 的文件代码。我仍然有这个问题。
  • EventEmitter 主要用于 Child=>Parent 通信。如果您是从 service=>component 进行通信,则应该使用 Subject/of。

标签: javascript angular typescript web-applications single-page-application


【解决方案1】:

服务:

import { Subject } from "rxjs";

export class NotificationService {
   private notifier = new Subject<string>();
   public notifier$ = this.notifier.asObservable();

   notify(message: string) {
      this.notifier.next(message);
   }
}

组件:

this.notificationService.notifier$
.subscribe(message => {
  this.message = message;
  this.snackVisibility = 'visible'; 
  setTimeout(()=>{
   this.snackVisibility = 'hidden';
  }, 2000);
});

【讨论】:

    猜你喜欢
    • 2022-06-12
    • 2018-04-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-26
    • 1970-01-01
    • 2019-03-19
    • 2015-10-24
    相关资源
    最近更新 更多