Estoy trabajando en una aplicación en la que debo configurar mensajes de acuerdo con la hora actual en función de las horas.
Por ejemplo, si la hora es: 23:35:2 , debo configurar una cadena para Good night <user name> y si la hora es 4:00:0 , quiero configurar Good morning <user name> en consecuencia.
Actualmente estoy escribiendo la lógica en BehaviourSubject del servicio angular. Obtengo la hora actual usando javascript. Pero después de que registré el valor en la consola, el tiempo está estáticamente allí.
let currentDate = new Date(); let time = currentDate.getHours() + ":" + currentDate.getMinutes() + ":" + currentDate.getSeconds(); console.log(time); Así que configuré un BehaviourSubject e intenté obtener el tiempo de forma dinámica, pero el valor sigue siendo estático.
A continuación se muestra mi código de archivo de servicio
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)); } }e intenté llamarlo en mi archivo de inicio de esta manera.
ngOnInit() { return this.appService.getDate(); } Recibo un error ERROR Error: Uncaught (in promise): TypeError: Cannot read properties of undefined (reading 'next')
Apenas soy nuevo en el oso angular conmigo. Agradeceré cualquier ayuda.
En servicio
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() ); }En tu componente:
time$: Observable<any>; constructor(private appService: AppService) { this.time$ = this.appService.getDate(); }en plantilla
Time {{ this.time$ | async }} Si desea aumentar el tiempo de retardo al intervalo ej. por cada 5 segundos simplemente cambie el parámetro de interval(5000) así como aquí this.date.setSeconds(this.date.getSeconds() + 5);