在许多组件中使用变量
我有此功能可以获取用户身份验证的时间,并且如果输入的数据有效,则可以在登录按钮上运行。我想在应用程序的许多不同组件中使用“ this.time”来显示用户身份验证时间,但是我不知道该怎么做,因为“ this.time”的价值不是静态的,有人可以帮助您我吗?如何将该价值获取到其他组件?
public sec = 0;
public min = 0;
public hour = 0;
public time: string;
startStopWatch() {
this.time = "00:00:00";
setInterval(() => {
console.log(this.time)
this.sec++;
this.time = (this.hour + ':' + this.min + ':' + this.sec);
if (this.sec === 60) {
this.min++;
this.sec = 0;
if (this.min === 60) {
this.hour++;
this.min = 0;
}
}
}, 1000);
}
I have this function to get the time the user is authenticated and it is running on the login button if the data entered is valid. I wanted to use that "this.time" in many different components of the application to show the user authentication time, but I don't know how to do that since the value of "this.time" is not static, could someone help me please? How do I get that value to other components?
public sec = 0;
public min = 0;
public hour = 0;
public time: string;
startStopWatch() {
this.time = "00:00:00";
setInterval(() => {
console.log(this.time)
this.sec++;
this.time = (this.hour + ':' + this.min + ':' + this.sec);
if (this.sec === 60) {
this.min++;
this.sec = 0;
if (this.min === 60) {
this.hour++;
this.min = 0;
}
}
}, 1000);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以通过服务使所有这些都可以访问,并且,由于看起来这与身份验证有关,因此您可以做一个不错的authservice。我提供了示例代码,该代码将提供您要寻找的功能。
在authservice中,
@injectable({suffenin:“ root”})
将使此服务具有全局范围,因此任何组件都可以访问。我提供了一个示例组件,向您展示了如何使用该授权服务并获取计时器信息。希望这有帮助!
auth.service.ts
示例组件
You can make all this accessible through a service, and, since it looks like this is all related to authentication, you can make a nice AuthService. I have provided example code that will provide the functionality you are looking for.
In the authService,
@Injectable({ providedIn: "root" })
will make this service have global scope, so any component will have access. I have provided an example component that shows you how to use that authService and get the timer info.Hope this helps!
auth.service.ts
Example Component