Ken*_*Ken 0 observable rxjs angular2-services angular
我正在尝试在Angular 2中建立一个非常基本的服务。目标是在用户单击按钮时显示当前日期和时间。当我使用下面的代码时,出现以下错误:
Error during evaluation of "click"
ORIGINAL EXCEPTION: TypeError: l_context.whatTime is not a function
时间部分:
@Component({
template: `
<h1>Time Test</h1>
<button (click) = "whatTime()">Time</button>
<h2>{{now}}</h2>
`
})
export class TimeComponent {
now = Date();
constructor(public timeService: TimeService) {
this.now = timeService.whatTime();
}
}
Run Code Online (Sandbox Code Playgroud)
服务:
@Injectable()
export class TimeService {
whatTime() {
return new Date();
}
}
Run Code Online (Sandbox Code Playgroud)
对我在做什么错有任何想法吗?
改用这个
<button (click) = "now = timeService.whatTime()">Time</button>
Run Code Online (Sandbox Code Playgroud)
但它可能会产生devmode错误。
更好的方法是Observable在服务中添加,以在预定义的时间间隔内通知时间更改
@Injectable()
export class TimeService {
constructor() {
this.whatTime = Observable.interval(1000).map(x => new Date()).share();
}
}
Run Code Online (Sandbox Code Playgroud)
<!-- <button (click) = "whatTime()">Time</button> -->
<h2>{{timeService?.whatTime | async}}</h2>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4924 次 |
| 最近记录: |