简体   繁体   English

应该如何声明一个空的时间戳变量,以便成为一个全局变量,以便我们稍后给它一个值?

[英]How should an empty timestamp variable be declared, in order to be a global var so we can give it a value later?

I want to set a timestamp as a global variable and set it with empty value.我想将时间戳设置为全局变量并将其设置为空值。 I want to use it inside the functions and assign a value to it.我想在函数中使用它并为其赋值。 How this timestamp var should be declared?应该如何声明这个时间戳变量?

For example, I have 2 buttons which each button triggers a method例如,我有 2 个按钮,每个按钮触发一个方法

<button (click)="startTime()">Starting timestamp</button>

<button (click)="endTime()">Ending timestamp</button>

I want to have two timestamp variables declared as global variables in component.ts, in order to get these dates when button are clicked and then update other methods.我想在 component.ts 中将两个时间戳变量声明为全局变量,以便在单击按钮时获取这些日期,然后更新其他方法。

Add the variable inside the class:在 class 中添加变量:

export class MyComponent {

  myTimestamp;
  myOtherTimestamp;

  startTime() {
    this.myTimestamp = new Date().getTime();
  }

  endTime() {
    this.myOtherTimestamp = new Date().getTime();
  }
}

For sharing with other components / services, you can add it to a singleton service and access it wherever you want:为了与其他组件/服务共享,您可以将其添加到 singleton 服务并在任何您想要的地方访问它:

@Injectable({
  providedIn: 'root',
})
export class MySharedService {
  myTimestamp;
}

and access it by injecting the service:并通过注入服务来访问它:

export class MyComponent {
  constructor(private mySharedService: MySharedService ){}

  myCustomFunction() {
   this.mySharedService.myTimestamp = new Date().getTime();
  }
}

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

相关问题 将类的文本值定义为全局变量,以便稍后在赛普拉斯中产生 - Define text value of class as global var, so it can be yield later in Cypress 未使用var声明的JavaScript变量是否变为全局变量? - Does a JavaScript variable not declared with var become global? 我们如何在量角器中保留全局变量的值? - How can we preserve the value of a global variable in protractor? 如何在每个循环中保存变量的值,以便以后可以使用这些值 - How do I save the value of a variable on each loop so I can use those values later 如何将获取数据存储到以后可以访问的全局变量中? - How to store fetch data into a global variable that you can access later? 创建全局“ for”变量。 应为“用于(可变项...” - Creating global 'for' variable. Should be 'for (var items …' 如何在不使用全局变量破坏其值的情况下为我的服务提供输入? - How can I give input to my service without crushing its value with a global variable? 在事件期间将值保存到全局变量中以供以后使用 - Save the value into global var during an event to be used for later 将值附加到全局变量名称中,稍后再调用 - Appending a value to a global variable name calling it later 在 Cypress 中如何产生 span 值,以便稍后进行比较 - How to yield span value in Cypress, so it can be compared later
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM