如何在可变打字稿中动态设置当前时间

How to set current time dynamically in a variable typescript

我正在开发一个应用程序,我应该根据当前时间设置消息。

例如,如果时间是:23:35:2 我应该将字符串设置为 Good night <user name>,如果时间到了 4:00:0,我想相应地设置 Good morning <user name>

目前我正在 angular 服务的 BehaviourSubject 中编写逻辑。我使用 javascript 获取当前时间。但是在我控制台记录该值之后,时间就在那里了。

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

所以我设置了一个 BehaviourSubject 并尝试动态获取时间,但该值仍然是静态的。

下面是我的服务文件代码

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

}

并尝试像这样在我的主文件中调用它。

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

我遇到错误 ERROR Error: Uncaught (in promise): TypeError: Cannot read properties of undefined (reading 'next')

我对 angular 并不陌生,请多多包涵。我将不胜感激任何帮助。

在役

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

在你的组件中:

 time$: Observable<any>;

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

在模板中

Time {{ this.time$ | async }}

Demo

如果您想将延迟时间增加到间隔 ex。每 5 秒只需更改 interval(5000) 参数以及此处 this.date.setSeconds(this.date.getSeconds() + 5);