使用 Angular 6 和 RxJs 6 显示时钟

Abh*_*har 4 javascript rxjs angular

如何使用 Angular 6 使用 rxjs 6 显示时钟。下面的代码适用于 angular 5。但现在我收到一条错误消息,说间隔不是 Observable 类型。

@Injectable()
export class MailService {

  private clock: Observable<Date>;


  constructor(private http : HttpClient) { 
    this.clock = Observable.interval(1000).map(tick => new Date()).share();
  }

  getClock(): Observable<Date> {
    return this.clock;
  }

}
Run Code Online (Sandbox Code Playgroud)

Fau*_*Chr 5

对于这些问题,我建议对Sachilacodeepic的给定答案进行一些小的改进:

  1. interval()运营商发出了超值的第一期已经过去之后(见文档
  2. 随着share()后续的认购可能错过了最后一跳并必须等待1秒,直到下一个数值到达。这可能会导致显示响应延迟。

解决方案:

  1. 使用timer(0, 1000):“它就像间隔,但您可以指定何时开始排放。” (见文档
  2. 使用shareReplay(1),其中1指示在新订阅上发出的先前发出的值的数量

代码(带有 RxJS 6 的 Angular 6):

import { Injectable } from "@angular/core";

import { Observable, timer } from "rxjs";
import { map, shareReplay } from "rxjs/operators";

@Injectable({
  providedIn: "root"
})
export class ClockService {
  private _time$: Observable<Date> = timer(0, 1000).pipe(
    map(tick => new Date()),
    shareReplay(1)
  );

  get time() {
    return this._time$;
  }

  constructor() {}
}  
Run Code Online (Sandbox Code Playgroud)

要访问时间:

import { ClockService } from "PATH/clock.service";

constructor(private _clockService: ClockService) {
   this._clockService.time.subscribe((now: Date) =>
     console.log("time:", now.toISOString())
   );
}
Run Code Online (Sandbox Code Playgroud)