简体   繁体   English

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

[英]Error when subscribing to time observable in Angular 2

I have a clock on my app that uses an observable to update every second: 我的应用程序上有一个时钟,该时钟使用observable每秒更新一次:

clock.service: 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: header.component:

...
private mydate: Date;

...
constructor(private clockService: ClockService, private alertService: AlertsService) { }

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

I'm getting an error: error TS2322: Type 'Subscription' is not assignable to type 'Date'. Property 'toDateString' is missing in type 'Subscription' 我收到错误消息: error TS2322: Type 'Subscription' is not assignable to type 'Date'. Property 'toDateString' is missing in type 'Subscription' 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);;
  }

This is wrong. 错了 You're binding subscription to Date , as the error says. 如错误所示,您将subscription绑定到Date Change to this: 更改为此:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM