为什么 Angular 组件的属性会被服务中实例化的计时器自动更新?

问题描述 投票:0回答:0

在我的 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()
时更新一次。

angular typescript angular-services angular-components
© www.soinside.com 2019 - 2024. All rights reserved.