我的应用上有一个时钟,它使用observable
每秒更新一次:
clock.service:
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'
答案 0 :(得分:2)
ngOnInit() {
this.mydate = this.clockService.getClock().subscribe(res => this.mydate = res);;
}
这是错误的。正如错误所述,您将subscription
绑定到Date
。
改为:
ngOnInit() {
this.clockService.getClock().subscribe(res => this.mydate = res);;
}