【发布时间】:2018-05-02 13:39:52
【问题描述】:
我有一个需要每秒返回日期的服务:
import { Injectable } from '@angular/core';
import {Observable} from 'rxjs/Observable';
@Injectable()
export class ClockService {
mydate: Date;
constructor() {
}
getClock(): Observable<any> {
setInterval(()=>{
this.mydate = new Date();
return this.mydate;
}, 1000);
}
}
我正在尝试订阅getClock() 函数来更新我的组件中的mydate:
import { Component, OnInit } from '@angular/core';
import {ClockService} from './clock.service';
@Component({
selector: 'app-header',
templateUrl: './header.component.html',
styleUrls: ['./header.component.scss']
})
export class HeaderComponent implements OnInit {
constructor(private clockService: ClockService) { }
ngOnInit() {
console.log(this.clockService.getClock().subscribe(res => this.mydate = res));
}
}
我收到了一个错误,ERROR TypeError: Cannot read property 'subscribe' of undefined
我是 Angular 2 的新手,文档没有帮助。
【问题讨论】:
-
您是否将该服务注册为
app.module的提供者? -
你应该
returnsetInterval
标签: angular rxjs angular2-services angular2-observables