metrics.service.ts
angular/examples/week05-06/metrics.service.ts
// @ts-nocheck
import { Injectable, inject } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable, Subject, shareReplay, switchMap, tap } from 'rxjs';
export interface MetricSummary {
id: string;
label: string;
value: number;
delta?: number;
}
@Injectable({ providedIn: 'root' })
export class MetricsService {
private http = inject(HttpClient);
private refresh$ = new Subject<void>();
private cache = new Map<string, Observable<unknown>>();
readonly summaries$ = this.refreshableRequest<MetricSummary[]>(() =>
this.http.get<MetricSummary[]>('/api/metrics/summary'),
);
refresh(): void {
this.refresh$.next();
}
fetchProjects(): Observable<{ name: string; status: string }[]> {
return this.http.get<{ name: string; status: string }[]>('/api/projects');
}
cacheResponse<T>(key: string) {
return (source$: Observable<T>) => {
const cached = this.cache.get(key) as Observable<T> | undefined;
if (cached) {
return cached;
}
const shared = source$.pipe(shareReplay({ bufferSize: 1, refCount: true }));
this.cache.set(key, shared);
return shared;
};
}
private refreshableRequest<T>(factory: () => Observable<T>): Observable<T> {
return this.refresh$.pipe(switchMap(() => factory()), shareReplay({ bufferSize: 1, refCount: true }));
}
ngOnInit(): void {
this.refresh();
}
}
Artigos relacionados
server.js
server.js — javascript source code from the angular learning materials (angular/comprehensive-demo/server/server.js).
Ler artigo →app.component.ts
app.component.ts — typescript source code from the angular learning materials (angular/comprehensive-demo/src/app/app.component.ts).
Ler artigo →app.config.ts
app.config.ts — typescript source code from the angular learning materials (angular/comprehensive-demo/src/app/app.config.ts).
Ler artigo →app.routes.ts
app.routes.ts — typescript source code from the angular learning materials (angular/comprehensive-demo/src/app/app.routes.ts).
Ler artigo →auth.guard.ts
auth.guard.ts — typescript source code from the angular learning materials (angular/comprehensive-demo/src/app/core/guards/auth.guard.ts).
Ler artigo →role.guard.ts
role.guard.ts — typescript source code from the angular learning materials (angular/comprehensive-demo/src/app/core/guards/role.guard.ts).
Ler artigo →