[英]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,它在您訂閱時返回一個日期:
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.