我试图在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;
}
}
答案 0 :(得分:3)
如果您想返回可观察值:
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
答案 1 :(得分:0)
让我们创建一个自定义可观察对象,该对象在您订阅时返回日期:
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);
}
}
注意:我没有尝试使用此代码,因此如果遇到错字或变量类型问题,请纠正我。