Home > Net >  How to set current time dynamically in a variable typescript
How to set current time dynamically in a variable typescript

Time:10-02

I'm working on a app which I should set messages according to current time based on hours.

For ex if time is: 23:35:2 I should set a string to Good night <user name> and if the time goes 4:00:0 I want to set Good morning <user name> accordingly.

Currently I'm writing the logic in angular service's BehaviourSubject. I get the current time by using javascript. But after I console logged the value the time is statically there.

let currentDate = new Date();
let time = currentDate.getHours()   ":"   currentDate.getMinutes()   ":"   currentDate.getSeconds();
console.log(time);

So I have set a BehaviourSubject and tried getting the time dynamically but the value is still static.

Below is my service file code

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class AppService {
  
  private time: BehaviorSubject<string>;

  constructor(private http:HttpClient) { }

  getDate() {
    let currentDate = new Date();
    let time = currentDate.getHours()   ":"   currentDate.getMinutes()   ":"   currentDate.getSeconds();
    console.log(time);
    return this.time.next(JSON.stringify(time));
  }   

}

and tried calling it in my home file like this.

ngOnInit() {
    return this.appService.getDate();
  }

I'm getting error ERROR Error: Uncaught (in promise): TypeError: Cannot read properties of undefined (reading 'next')

I'm barely new to angular bear with me. I'll appreciate any help.

CodePudding user response:

In service

  date = new Date();
  
  getDate() {
    return interval(1000).pipe(map(_ => this.getDateTime()));
  }

  // get new time by adding   sec
  private getDateTime() {
    this.date.setSeconds(this.date.getSeconds()   1);
    return (
      this.date.getHours()  
      ':'  
      this.date.getMinutes()  
      ':'  
      this.date.getSeconds()
    );
  }

In your component :

 time$: Observable<any>;

  constructor(private appService: AppService) {
    this.time$ = this.appService.getDate();
  }

In template

Time {{ this.time$ | async }}

Demo

If you want to increase delay time to the interval ex. for every 5 sec just change interval(5000) parameter as well as here this.date.setSeconds(this.date.getSeconds() 5);

  • Related