在我的 Angular 项目中,我定义了:
myService
MainComponent
myService
该服务包含一个计时器,该计时器在启动时更新属性
currentTime
。 myService.service.ts
文件是:
import { Injectable } from '@angular/core';
export interface Parameters {
currentTime: string;
}
@Injectable({
providedIn: 'root'
})
export class myService {
acquireParametersTimer!: ReturnType<typeof setTimeout>;
timerStarted:boolean = false;
par:Parameters = {
currentTime: ''
};
constructor() {}
startAcquire(): void {
if (this.timerStarted == false) {
this.acquireParametersTimer = setTimeout(() => {this.acquireParameters()}, 1000);
this.timerStarted = true;
}
}
acquireParameters() {
const d = new Date();
this.par.currentTime = d.toLocaleTimeString();
this.acquireParametersTimer = setTimeout(() => {this.acquireParameters()}, 1000);
}
getParameters():Parameters {
return this.par;
}
}
MainComponent
组件启动服务中存在的计时器,并通过方法
getParameters()
调用服务的方法ngOnInit()
。文件main.component.ts
是:
import { Component, OnInit } from '@angular/core';
import { myService, Parameters } from 'src/app/services/myService.service';
@Component({
selector: 'app-main',
templateUrl: './main.component.html',
styleUrls: ['./main.component.css']
})
export class MainComponent implements OnInit {
par:Parameters = {
currentTime: ''
};
constructor(private my_service: myService) {
my_service.startAcquire();
}
ngOnInit(): void {
this.par = this.my_service.getParameters();
}
}
文件
main.component.html
包含以下代码:
<div>
<span>{{par.currentTime}}</span>
</div>
如果我通过命令启动 Angular 应用程序:
> ng serve -o
我可以在
6:58:12 PM
标签中看到(例如)时间<span>
,在1000毫秒后<span>
显示时间6:58:13 PM
等等。这意味着时间增加了,但我只调用了一次服务的方法getParameters()
。
如果我在
getParameters()
中只调用一次方法ngOnInit()
,为什么<span>
标签每1000毫秒更新一次?我原以为它只会在执行方法ngOnInit()
时更新一次。