Akash Mule
Akash Mule

Reputation: 11

Broadcast Event In Angular 13 ( same as $rootScope.$broadcast( ) in AngularJS )

I want to implement the connection between All modules and components with event broadcasting . If I broadcast one event in one component it should be received in root module as well as any grand child component . How to achieve this . I have used AngularJS , It provides $rootScope.$broadcast( ) for broadcasting events, How to Implement it in Angular 13 what is the best Practice to achieve this functionality

Upvotes: 0

Views: 873

Answers (1)

Charlie V
Charlie V

Reputation: 1040

I would implement a service that has a private BehaviorSubject and a public Observable that can be subscribed to. Additionally some functions to 'send' messages. A starting point could be:

broadcast.service.ts

import { Injectable } from '@angular/core';
import {BehaviorSubject} from "rxjs";

@Injectable({
  providedIn: 'root'
})
export class BroadcastService {

  private messageSubject: BehaviorSubject<string> = new BehaviorSubject<string>("Initial message")
  broadcastMessage$ = this.messageSubject.asObservable()
  
  constructor() { }

  sendMessage(message: string){
    this.messageSubject.next(message);
  }
}

Upvotes: 0

Related Questions