I have 2 roles, Admin and Watcher, the admin has the ability to make changes to a table and upload them to a DB, the watcher can't make changes to that table, it can only visualize the data, the problem is that whenever an admin makes a (PUT, POST, DELETE) change to the table, the watcher only receives it if the page is reloaded, i want the change to be seen in the watcher component without the page being reloaded, immediatly when the admin makes a change to the table.
I've tried making a shared service that notifies the watcher whenever there's a change in the table:
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
@Injectable({
providedIn: 'root',
})
export class ActionPlanSharedService {
private tableUpdated = new BehaviorSubject<boolean>(false);
// Observable para que otros componentes puedan suscribirse a los cambios
tableUpdated$ = this.tableUpdated.asObservable();
constructor() {}
// Método para notificar que los datos han cambiado
notifyTableUpdate(): void {
this.tableUpdated.next(true);
}
}
Watcher component:
private subscription!: Subscription;
ngOnInit(): void {
this.getTableData(); // Cargar datos iniciales
this.subscription = this.actionPlanSharedService.tableUpdated$.subscribe((updated) => {
if (updated) {
this.getTableData();
this.getUpdatedAt();
}
});
}
ngOnDestroy(): void {
this.subscription.unsubscribe();
}
Admin component:
deleteRow(): void {
const id = this.id;
this.actionPlanService.deleteActionPlan(id).subscribe({
next: () => {
this.toastr.success('Registro eliminado exitosamente');
this.getTableData();
this.actionPlanSharedService.notifyTableUpdate();
},
error: (err) => {
this.toastr.error('Error al eliminar el registro', err.message);
console.error('Error al eliminar el registro', err);
},
});
}
I think the error here is that the subscription is only make when the component starts, but even if there is a change, this component will not receive it because the subscription is already made and the value is already stablished (false). I was thinking of inserting the subscription in a ngOnChanges and detect if the table have been modified, but i dont know how to do it.
For real-time data from the client, you have several options like (Websocket, Server-Sent events, Long Polling, etc.)
You just want to see updated data from the watcher's perspective like live score. In that case, you don't need two-way data communication like a web socket. You can simply use SSE or Long Polling.