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组件:
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();
}
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);
},
});
}
我认为这里的错误是仅在组件启动时进行订阅,但是即使有更改,此组件也不会收到它,因为已经进行了订阅,并且该值已经稳定了(false)。 我正在考虑将订阅插入ngonchanges,并检测到桌子是否已修改,但我不知道该怎么做。
当@Browsermator在评论中说,您必须使用Websockets,因为无论您在服务中做出什么变化,观察者的视图都不会更新,因为代码在不同的环境中运行。