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



我想将时间戳设置为全局变量,并将其设置为空值。我想在函数中使用它,并为它赋值。这个时间戳var应该如何声明?

例如,我有两个按钮,每个按钮都会触发一个方法

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

我希望在component.ts中有两个时间戳变量声明为全局变量,以便在单击按钮时获得这些日期,然后更新其他方法。

在类中添加变量:

export class MyComponent {
myTimestamp;
myOtherTimestamp;
startTime() {
this.myTimestamp = new Date().getTime();
}
endTime() {
this.myOtherTimestamp = new Date().getTime();
}
}

为了与其他组件/服务共享,您可以将其添加到单例服务中,并在任何您想要的地方访问它:

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

并通过注入服务来访问它:

export class MyComponent {
constructor(private mySharedService: MySharedService ){}
myCustomFunction() {
this.mySharedService.myTimestamp = new Date().getTime();
}
}

最新更新