Ir al contenido

Angular

En Angular, el lugar natural para Tabus es un servicio providedIn: 'root' que implementa OnDestroy para limpiar el bus cuando Angular destruye el servicio.

import { Injectable, OnDestroy } from "@angular/core";
import { Tabus } from "tabus-js";
@Injectable({ providedIn: "root" })
export class TabSyncService implements OnDestroy {
private bus = new Tabus<{ "cart:add": { id: string } }>("shop");
onAdd = (cb: (id: string) => void) => {
this.bus.on("cart:add", ({ id }) => cb(id));
};
ngOnDestroy = () => this.bus.destroy();
}

Y en el componente:

@Component({ selector: "app-cart", template: `...` })
export class CartComponent implements OnInit {
items: string[] = [];
constructor(private tabSync: TabSyncService) {}
ngOnInit() {
this.tabSync.onAdd((id) => this.items.push(id));
}
}

Al registrar el servicio como singleton de raíz, todos los componentes que lo inyectan comparten la misma instancia de Tabus — y por lo tanto el mismo canal. ngOnDestroy solo se dispara cuando Angular destruye el servicio (normalmente al destruir la app), no en cada componente.

Revisa el ejemplo completo de carrito compartido, que amplía este mismo patrón.