簡體   English   中英

類型&#39;日期&#39;不能分配給&#39;Observable&#39;類型 <Date> &#39; - Angular 6+

[英]Type 'Date' is not assignable to type 'Observable<Date>' - Angular 6+

我試圖在Angular中制作一個簡單的時鍾,但我似乎無法使Observable / Subscription工作。

它不斷拋出錯誤:

類型'日期'不能分配給'Observable'類型

我在這里錯過了什么嗎?

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:

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

工作演示

更新 rxjs 6+

你應該這樣導入:

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

並以這種方式使用間隔:

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

工作演示

讓我們創建一個自定義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);
  }

}

注意:我沒有嘗試代碼,所以如果有拼寫錯誤或變量類型的問題,請糾正我。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM