import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { SERVER_API_URL } from 'app/app.constants'; export interface BroadCastMessage { message: string; starts_at: Date; ends_at: Date; color: string; font: string; id: number; active: boolean; // false, target_path: string; // "*/welcome", broadcast_type: string; // "banner", dismissable: boolean; // false } /** provides infrastructure services for Plugins */ @Injectable({ providedIn: 'root' }) export class MessageService { public messageResourceURL = SERVER_API_URL + 'api/applicationInfo/broadcastMessages'; private messages = new Array<BroadCastMessage>(); private nextUpdate = 0; constructor(protected http: HttpClient) {} public getActiveMessages(): Array<BroadCastMessage> { const now = new Date(); return this.getMessages().filter(m => m.starts_at <= now && m.ends_at >= now); // } public getMessages(): Array<BroadCastMessage> { const now = new Date().getTime(); if (this.nextUpdate > now) { return this.messages; } this.nextUpdate = now + 60 * 1000; // wait at least 1 Minute for next try const resp = this.http.get<Array<BroadCastMessage>>(this.messageResourceURL); resp.subscribe(response => { // first convert dates correctly :-( response.forEach(m => { // eslint-disable-next-line @typescript-eslint/camelcase m.starts_at = new Date(m.starts_at); // eslint-disable-next-line @typescript-eslint/camelcase m.ends_at = new Date(m.ends_at); }); // Data will be cached this.messages = response; this.nextUpdate = new Date().getTime() + 10 * 60 * 1000; // wait 10 Minute for next try return response; }); return this.messages; } }