【问题标题】:Type 'Date' is not assignable to type 'Observable<Date>' - Angular 6+类型“日期”不可分配给类型“Observable<Date>” - Angular 6+
【发布时间】:2018-08-25 10:39:00
【问题描述】:

我正在尝试在 Angular 中制作一个简单的时钟,但我似乎无法让 Observable/Subscription 正常工作。

一直报错:

类型“日期”不可分配给类型“可观察”

我错过了什么吗?

clock.service.ts

export class ClockService {

  private clock: Observable<Date>;

  constructor() {
    setInterval(() => {
      this.clock = new Date();
    }, 1000);
  }

  getCurrentTime() {
    return this.clock;
  }
}

clock.component.ts

export class ClockComponent implements OnInit {

  private time;

  constructor(private clockService: ClockService) { }

  ngOnInit() {
    this.time = this.clockService.getCurrentTime.subscribe;
  }

}

【问题讨论】:

  • 您声明了Observable&lt;Date&gt; 类型的点击,但您尝试分配new Date,它不是Observable

标签: javascript angular typescript observable


【解决方案1】:

如果你想返回 observable:

this.clock = Observable.interval(1000).map(() => new Date());

工作DEMO

rxjs 6+

更新

你应该这样导入:

import { Observable , interval} from 'rxjs';
import { map } from 'rxjs/operators';

并以这种方式使用间隔:

this.clock = interval(1000).pipe(map(() => new Date());

工作DEMO

【讨论】:

  • 我的 IDE 不喜欢 Observable 上的 .interval()...Property interval doesn't exist on type 'typeof Observable
  • 哪个版本的 rxjs?
  • 6.0.0 - 我确实做到了ng new clock-app,所以这正是 CLI 下载它的方式。可能与检查 CLI 上的更新有关
  • 啊太棒了!感谢您抽出宝贵时间:-)
【解决方案2】:

让我们创建一个自定义的 observable,它返回您订阅的日期:

export class ClockService {

  private clock;

  constructor() {
    // create observable
    this.clock = new Observable((observer) => {        
    // observable execution
    observer.next(setInterval(() => new Date(), 1000);)
    });
  }

  getClock() {
    return this.clock;
  }
}

使用服务:

export class ClockComponent implements OnInit {

  private time;

  constructor(private clockService: ClockService) { }

  ngOnInit() {
    this.time = this.clockService.getClock.subscribe((date) => this.time = 
  date.getCurrentTime);
  }

}

注意:我没有尝试代码,所以如果有错字或变量类型问题,请纠正我。

【讨论】:

    猜你喜欢
    • 2018-11-02
    • 2022-06-25
    • 2021-05-21
    • 1970-01-01
    • 2020-11-23
    • 2019-01-12
    • 2020-07-29
    • 2018-08-14
    • 2021-01-02
    相关资源
    最近更新 更多