定期用 Angular 为 http-get 更新订阅

Periodically renew Subscription with Angular for http-get

我想从服务器定期调用 Angular 前端的方法。我只想收到当前时间。我的问题是浏览器的内存使用量越来越大!

我不确定订阅是每秒更新一次还是仅在触发时才更新。因此,如果调用需要几秒钟,订阅在这段时间内不会更新十次 - 当然有可能作为初学者我在程序中犯了几个错误...

我的服务:

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

export interface timestamp {
    now: number;
}

@Injectable({
    providedIn: 'root'
})

export class FireCrewService {

    private api = 'api/';

    constructor(private http: HttpClient) { }

    getToday(): Observable<timestamp> {
        return this.http.get<any>(`${this.api}today`);
    }

}

我的组件:

import { Component, OnInit, OnDestroy } from '@angular/core';
import { FireCrewService, timestamp } from '..//shared/fire-crew.service';

import { interval, of, Subject } from 'rxjs';
import { catchError, mergeMap, takeUntil } from 'rxjs/operators'

@Component({
    selector: 'app-default',
    templateUrl: './default.component.html',
    styleUrls: ['./default.component.css']
})

export class DefaultComponent implements OnInit, OnDestroy {

    today: timestamp | undefined;
    destroy$ = new Subject();

    constructor(private fs: FireCrewService) {
    }

    ngOnDestroy(): void {
        this.destroy$.next();
    }


    ngOnInit(): void {

    const myObserver = {
        next: (value: timestamp) => this.onNext(value),
        error: (err: string) => this.onError(err),
        complete: () => this.onComplete(),
    };

    interval(1000).pipe(
        mergeMap(
            () => this.fs.getToday().pipe(
                    catchError((err) => {
                    this.onError(err);
                    return of(err);
                    })
                )
            ), takeUntil(this.destroy$)
        ).subscribe(myObserver);

    }


    onNext(value: timestamp): void {
        this.today = value;
    }

    onError(value: string): void {
        console.log('Observer got a onError notification', value);
    }

    onComplete(): void {
        console.log('Observer got a complete notification')
    }

}

我可以自己解决:

ngOnDestroy(): void {
  this.destroy$.next();
}

ngOnInit(): void {
  this.fs.getLast().pipe(takeUntil(this.destroy$)).subscribe(this.myObserver);
}

onNext(value: timestamp): void {
  this.timestamp = timestamp;
}

onError(value: string): void {
  setTimeout(() => this.fs.getLast()
  .pipe(takeUntil(this.destroy$)).subscribe(this.myObserver), 5000);
}

onComplete(): void {
  setTimeout(() => this.fs.getLast()
  .pipe(takeUntil(this.destroy$)).subscribe(this.myObserver), 1000);
}