Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

177
Visualizações
How to set current time dynamically in a variable typescript

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.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda