[英]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.