【发布时间】:2021-07-10 04:09:52
【问题描述】:
我想定期从服务器调用我的 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')
}
}
【问题讨论】:
-
您可以使用计时器运算符进行检查:learnrxjs.io/learn-rxjs/operators/creation/timer 也许它是适合您用例的运算符
标签: angular typescript subscription