最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

typescript - Update of a (role) component when a HTTP operation is made by an Admin component in Angular - Stack Overflow

programmeradmin1浏览0评论

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.

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.

Share Improve this question asked Feb 7 at 17:40 Fernando HernandezFernando Hernandez 1 New contributor Fernando Hernandez is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct. 1
  • 1 if want the results "live" you'll need to use websockets: rxjs.dev/api/webSocket/webSocket – browsermator Commented Feb 7 at 18:27
Add a comment  | 

2 Answers 2

Reset to default 0

As @browsermator said in the comments, you'll have to use websockets since no matter what change you make in your service, the Watcher's view won't be updated as the code runs in a different environment than the Admin.

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.

发布评论

评论列表(0)

  1. 暂无评论