订阅 Angular 2 中可观察到的时间时出错



我的应用程序上有一个时钟,它使用observable每秒更新一次:

时钟服务:

import { Injectable } from '@angular/core';
import {Observable} from 'rxjs/observable';
@Injectable()
export class ClockService {
mydate: Date;
constructor() {}
getClock(): Observable<any> {
return new Observable(observer => {
setInterval(()=>{
this.mydate = new Date();
observer.next(this.mydate);
}, 1000);
});
}
}

header.component:

...
private mydate: Date;
...
constructor(private clockService: ClockService, private alertService: AlertsService) { }
ngOnInit() {
this.mydate = this.clockService.getClock().subscribe(res => this.mydate = res);;
}

我收到错误:error TS2322: Type 'Subscription' is not assignable to type 'Date'. Property 'toDateString' is missing in type 'Subscription'

ngOnInit() {
this.mydate = this.clockService.getClock().subscribe(res => this.mydate = res);;
}

这是错误的。正如错误所说,您将subscription绑定到Date。 更改为此内容:

ngOnInit() {
this.clockService.getClock().subscribe(res => this.mydate = res);;
}

最新更新