Search code examples
angulartypescriptangular-components

Use a variable in many components Angular


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);
  }

Solution

  • 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

    import { Injectable } from "@angular/core";
    
    @Injectable({ providedIn: "root" })
    export class AuthService {
    
      private isAuth: boolean;
    
      private sec = 0;
      private min = 0;
      private hour = 0;
      private time: string;      
    
    
      constructor() {}
    
      public login(){
        /* authentication logic here
        
        If authenticated, then this.startStopWatch()
        
        */
      }
    
      private 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);
        }
    
      public getTimer(){
        return this.time;
      }
    
    }
    

    Example Component

    import { Component} from '@angular/core';
    
    @Component({
      selector: 'app-test',
      templateUrl: './test.component.html',
      styleUrls: ['./test.component.scss']
    })
    export class TestComponent{
    
      constructor(private authService: AuthService) { }
    
      testFunction(){
    
        console.log(this.authService.getTimer())
    
      }
    
    }