我想从服务器定期调用Angular Frontend上的一个方法。我只想收到当前时间。我的问题是浏览器的内存使用量越来越大!
我不确定订阅是每秒钟续订一次,还是只有在它启动时才续订。因此,如果通话需要几秒钟,在此期间订阅不会续订十次-当然,作为一个初学者,我可能在程序中犯了几个错误。。。
我的服务:
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);
}